rewrite to using new method
This commit is contained in:
@@ -3,18 +3,42 @@ package controller
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/caarlos0/env/v6"
|
||||
"github.com/joho/godotenv"
|
||||
httpSwagger "github.com/swaggo/http-swagger"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"gitlab.com/DeveloperDurp/DurpAPI/model"
|
||||
"gitlab.com/DeveloperDurp/DurpAPI/storage"
|
||||
"gitlab.com/DeveloperDurp/DurpAPI/middleware"
|
||||
"gitlab.com/DeveloperDurp/DurpAPI/services/dadjoke"
|
||||
"gitlab.com/DeveloperDurp/DurpAPI/services/health"
|
||||
"gitlab.com/DeveloperDurp/DurpAPI/services/openai"
|
||||
"gitlab.com/developerdurp/stdmodels"
|
||||
)
|
||||
|
||||
type Controller struct {
|
||||
Cfg model.Config
|
||||
Dbcfg model.DBConfig
|
||||
Db model.Repository
|
||||
Cfg Config
|
||||
Dbcfg DBConfig
|
||||
Db *gorm.DB
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
Host string `env:"host"`
|
||||
Version string `env:"version"`
|
||||
Groupsenv string `env:"groupsenv"`
|
||||
JwksURL string `env:"jwksurl"`
|
||||
LlamaURL string `env:"llamaurl"`
|
||||
}
|
||||
|
||||
type DBConfig struct {
|
||||
Host string `env:"db_host"`
|
||||
Port string `env:"db_port"`
|
||||
Password string `env:"db_pass"`
|
||||
User string `env:"db_user"`
|
||||
DBName string `env:"db_name"`
|
||||
SSLMode string `env:"db_sslmode"`
|
||||
}
|
||||
|
||||
func NewController() *Controller {
|
||||
@@ -24,8 +48,8 @@ func NewController() *Controller {
|
||||
}
|
||||
|
||||
controller := &Controller{
|
||||
Cfg: model.Config{},
|
||||
Dbcfg: model.DBConfig{},
|
||||
Cfg: Config{},
|
||||
Dbcfg: DBConfig{},
|
||||
}
|
||||
|
||||
err = env.Parse(&controller.Cfg)
|
||||
@@ -37,11 +61,77 @@ func NewController() *Controller {
|
||||
log.Fatalf("unable to parse database variables: %e", err)
|
||||
}
|
||||
|
||||
Db, err := storage.Connect(controller.Dbcfg)
|
||||
Db, err := connectDB(controller.Dbcfg)
|
||||
if err != nil {
|
||||
panic("Failed to connect to database")
|
||||
}
|
||||
controller.Db = *Db
|
||||
controller.Db = Db
|
||||
|
||||
return controller
|
||||
}
|
||||
|
||||
func (c *Controller) Run() error {
|
||||
|
||||
router := http.NewServeMux()
|
||||
|
||||
err := c.loadAll(router)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
stack := middleware.CreateStack(
|
||||
middleware.Logging,
|
||||
middleware.Headers,
|
||||
)
|
||||
|
||||
server := http.Server{
|
||||
Addr: ":8080",
|
||||
Handler: stack(router),
|
||||
}
|
||||
|
||||
fmt.Println("Server listening on port :8080")
|
||||
return server.ListenAndServe()
|
||||
}
|
||||
|
||||
func (c *Controller) loadAll(router *http.ServeMux) error {
|
||||
|
||||
// adminRouter := http.NewServeMux()
|
||||
|
||||
// router.Handle("/", middleware.EnsureAdmin(adminRouter))
|
||||
|
||||
router.HandleFunc("/", defaultHandler)
|
||||
router.HandleFunc("/swagger/*", httpSwagger.Handler())
|
||||
|
||||
health, err := health.NewHandler()
|
||||
router.HandleFunc("GET /api/health/gethealth", health.Get)
|
||||
|
||||
dadjoke, err := dadjoke.NewHandler(c.Db)
|
||||
router.HandleFunc("GET /api/jokes/dadjoke", dadjoke.Get)
|
||||
router.HandleFunc("POST /api/jokes/dadjoke", dadjoke.Post)
|
||||
router.HandleFunc("DELETE /api/jokes/dadjoke", dadjoke.Delete)
|
||||
|
||||
openai, err := openai.NewHandler(c.Cfg.LlamaURL)
|
||||
router.HandleFunc("GET /api/openai/general", openai.GeneralOpenAI)
|
||||
router.HandleFunc("GET /api/openai/travelagent", openai.TravelAgentOpenAI)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func defaultHandler(w http.ResponseWriter, r *http.Request) {
|
||||
stdmodels.FailureReponse("Page Does not exist", w, http.StatusNotFound, []string{"Page is not found"})
|
||||
}
|
||||
|
||||
func connectDB(config DBConfig) (*gorm.DB, error) {
|
||||
dsn := fmt.Sprintf(
|
||||
"host=%s port=%s user=%s password=%s dbname=%s sslmode=%s",
|
||||
config.Host, config.Port, config.User, config.Password, config.DBName, config.SSLMode,
|
||||
)
|
||||
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return db, nil
|
||||
}
|
||||
|
||||
@@ -1,124 +0,0 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"gitlab.com/DeveloperDurp/DurpAPI/model"
|
||||
"gitlab.com/DeveloperDurp/DurpAPI/service"
|
||||
"gitlab.com/developerdurp/logger"
|
||||
"gitlab.com/developerdurp/stdmodels"
|
||||
)
|
||||
|
||||
// GetDadJoke godoc
|
||||
//
|
||||
// @Summary Get dadjoke
|
||||
// @Description get a dad joke
|
||||
// @Tags DadJoke
|
||||
// @Accept json
|
||||
// @Produce application/json
|
||||
// @Success 200 {object} model.Message "response"
|
||||
// @failure 500 {object} stdmodels.StandardError"error"
|
||||
//
|
||||
// @Security Authorization
|
||||
//
|
||||
// @Router /jokes/dadjoke [get]
|
||||
func (c *Controller) GetDadJoke(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
joke, err := service.GetRandomDadJoke(c.Db.DB)
|
||||
|
||||
if err != nil {
|
||||
stdmodels.FailureReponse("Failed to get Joke", w, http.StatusInternalServerError, []string{err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
message := model.Message{
|
||||
Message: joke,
|
||||
}
|
||||
|
||||
json.NewEncoder(w).Encode(message)
|
||||
}
|
||||
|
||||
// PostDadJoke godoc
|
||||
//
|
||||
// @Summary Generate dadjoke
|
||||
// @Description create a dad joke
|
||||
// @Tags DadJoke
|
||||
// @Accept json
|
||||
// @Produce application/json
|
||||
// @Param joke query string true "Dad Joke you wish to enter into database"
|
||||
// @Success 200 {object} model.Message "response"
|
||||
// @failure 500 {object} stdmodels.StandardError"error"
|
||||
//
|
||||
// @Security Authorization
|
||||
//
|
||||
// @Router /jokes/dadjoke [post]
|
||||
func (c *Controller) PostDadJoke(w http.ResponseWriter, r *http.Request) {
|
||||
contentType := r.Header.Get("Content-Type")
|
||||
var req model.DadJoke
|
||||
|
||||
if contentType == "application/json" {
|
||||
err := json.NewDecoder(r.Body).Decode(&req)
|
||||
if err != nil {
|
||||
logger.LogError("Failed to decode json file")
|
||||
return
|
||||
}
|
||||
} else {
|
||||
queryParams := r.URL.Query()
|
||||
req.JOKE = queryParams.Get("joke")
|
||||
}
|
||||
|
||||
err := service.PostDadJoke(c.Db.DB, req)
|
||||
if err != nil {
|
||||
stdmodels.FailureReponse("Failed to add joke", w, http.StatusInternalServerError, []string{err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
stdmodels.SuccessResponse("OK", w, http.StatusOK)
|
||||
}
|
||||
|
||||
// DeleteDadJoke godoc
|
||||
//
|
||||
// @Summary Generate dadjoke
|
||||
// @Description create a dad joke
|
||||
// @Tags DadJoke
|
||||
// @Accept json
|
||||
// @Produce application/json
|
||||
// @Param joke query string true "Dad joke you wish to delete from the database"
|
||||
// @Success 200 {object} model.Message "response"
|
||||
// @failure 500 {object} stdmodels.StandardError"error"
|
||||
//
|
||||
// @Security Authorization
|
||||
//
|
||||
// @Router /jokes/dadjoke [delete]
|
||||
func (c *Controller) DeleteDadJoke(w http.ResponseWriter, r *http.Request) {
|
||||
contentType := r.Header.Get("Content-Type")
|
||||
var req model.DadJoke
|
||||
|
||||
if contentType == "application/json" {
|
||||
err := json.NewDecoder(r.Body).Decode(&req)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
w.Write([]byte(http.StatusText(http.StatusInternalServerError)))
|
||||
return
|
||||
}
|
||||
} else {
|
||||
queryParams := r.URL.Query()
|
||||
req.JOKE = queryParams.Get("joke")
|
||||
}
|
||||
|
||||
err := service.DeleteDadJoke(c.Db.DB, req)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
w.Write([]byte(http.StatusText(http.StatusInternalServerError)))
|
||||
return
|
||||
}
|
||||
|
||||
message := model.Message{
|
||||
Message: "OK",
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(message)
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"gitlab.com/developerdurp/logger"
|
||||
"gitlab.com/developerdurp/stdmodels"
|
||||
)
|
||||
|
||||
// getHealth godoc
|
||||
//
|
||||
// @Summary Generate Health status
|
||||
// @Description Get the health of the API
|
||||
// @Tags health
|
||||
// @Accept json
|
||||
// @Produce application/json
|
||||
// @Success 200 {object} model.Message "response"
|
||||
// @failure 500 {object} model.Message "error"
|
||||
//
|
||||
// @Security Authorization
|
||||
//
|
||||
// @Router /health/gethealth [get]
|
||||
func (c *Controller) GetHealth(w http.ResponseWriter, r *http.Request) {
|
||||
logger.LogInfo("Health Check")
|
||||
stdmodels.SuccessResponse("OK", w, http.StatusOK)
|
||||
}
|
||||
@@ -1,154 +0,0 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"gitlab.com/DeveloperDurp/DurpAPI/model"
|
||||
)
|
||||
|
||||
type ChatRequest struct {
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// Response struct to unmarshal the JSON response
|
||||
type Response struct {
|
||||
Response string `json:"response"`
|
||||
}
|
||||
|
||||
// GeneralOpenAI godoc
|
||||
//
|
||||
// @Summary Gerneral ChatGPT
|
||||
// @Description Ask ChatGPT a general question
|
||||
// @Tags openai
|
||||
// @Accept json
|
||||
// @Produce application/json
|
||||
// @Param message query string true "Ask ChatGPT a general question"
|
||||
// @Success 200 {object} model.Message "response"
|
||||
//
|
||||
// @failure 400 {object} model.Message "error"
|
||||
//
|
||||
// @Security Authorization
|
||||
//
|
||||
// @Router /openai/general [get]
|
||||
func (c *Controller) GeneralOpenAI(w http.ResponseWriter, r *http.Request) {
|
||||
contentType := r.Header.Get("Content-Type")
|
||||
var req ChatRequest
|
||||
|
||||
if contentType == "application/json" {
|
||||
err := json.NewDecoder(r.Body).Decode(&req)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
w.Write([]byte(http.StatusText(http.StatusInternalServerError)))
|
||||
return
|
||||
}
|
||||
} else {
|
||||
queryParams := r.URL.Query()
|
||||
req.Message = queryParams.Get("message")
|
||||
}
|
||||
|
||||
result, err := c.createChatCompletion(req.Message, "mistral:instruct")
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
w.Write([]byte(http.StatusText(http.StatusInternalServerError)))
|
||||
return
|
||||
}
|
||||
|
||||
message := model.Message{
|
||||
Message: result,
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(message)
|
||||
}
|
||||
|
||||
// TravelAgentOpenAI godoc
|
||||
//
|
||||
// @Summary Travel Agent ChatGPT
|
||||
// @Description Ask ChatGPT for suggestions as if it was a travel agent
|
||||
// @Tags openai
|
||||
// @Accept json
|
||||
// @Produce application/json
|
||||
// @Param message query string true "Ask ChatGPT for suggestions as a travel agent"
|
||||
// @Success 200 {object} model.Message "response"
|
||||
// @failure 400 {object} model.Message "error"
|
||||
//
|
||||
// @Security Authorization
|
||||
//
|
||||
// @Router /openai/travelagent [get]
|
||||
func (c *Controller) TravelAgentOpenAI(w http.ResponseWriter, r *http.Request) {
|
||||
contentType := r.Header.Get("Content-Type")
|
||||
var req ChatRequest
|
||||
|
||||
if contentType == "application/json" {
|
||||
err := json.NewDecoder(r.Body).Decode(&req)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
w.Write([]byte(http.StatusText(http.StatusInternalServerError)))
|
||||
return
|
||||
}
|
||||
} else {
|
||||
queryParams := r.URL.Query()
|
||||
req.Message = queryParams.Get("message")
|
||||
}
|
||||
|
||||
req.Message = "I want you to act as a travel guide. I will give you my location and you will give me suggestions. " + req.Message
|
||||
|
||||
result, err := c.createChatCompletion(req.Message, "mistral:instruct")
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
w.Write([]byte(http.StatusText(http.StatusInternalServerError)))
|
||||
return
|
||||
}
|
||||
|
||||
message := model.Message{
|
||||
Message: result,
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(message)
|
||||
}
|
||||
|
||||
func (c *Controller) createChatCompletion(message string, model string) (string, error) {
|
||||
// Define the request body
|
||||
requestBody := map[string]interface{}{
|
||||
"model": model,
|
||||
"prompt": message,
|
||||
"stream": false,
|
||||
}
|
||||
|
||||
// Convert the request body to JSON
|
||||
requestBodyBytes, err := json.Marshal(requestBody)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error encoding request body: %v", err)
|
||||
}
|
||||
|
||||
// Send a POST request to the specified URL with the request body
|
||||
response, err := http.Post(
|
||||
"http://"+c.Cfg.LlamaURL+"/api/generate",
|
||||
"application/json",
|
||||
bytes.NewBuffer(requestBodyBytes),
|
||||
)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error sending POST request: %v", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
// Read the response body
|
||||
responseBody, err := io.ReadAll(response.Body)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error reading response body: %v", err)
|
||||
}
|
||||
|
||||
// Unmarshal the JSON response
|
||||
var resp Response
|
||||
if err := json.Unmarshal(responseBody, &resp); err != nil {
|
||||
return "", fmt.Errorf("error decoding response body: %v", err)
|
||||
}
|
||||
|
||||
// Return the response
|
||||
return resp.Response, nil
|
||||
}
|
||||
Reference in New Issue
Block a user