diff --git a/cocopasty-backend/database.go b/cocopasty-backend/database.go index de96f70..8f44fa4 100644 --- a/cocopasty-backend/database.go +++ b/cocopasty-backend/database.go @@ -8,52 +8,39 @@ import ( log "github.com/sirupsen/logrus" ) -var connection *redis.Client -var ctx context.Context +type database struct { + connection *redis.Client +} const keyName = "cocopasty-code-snippet" -func createConnection() { +func CreateDatabaseClient() (*database, error) { setLogLevel() log.Debug("Creating connection to Redis...") - connection = redis.NewClient(&redis.Options{ + + redisConnection := redis.NewClient(&redis.Options{ Network: "tcp", Addr: getAddress(), Password: getPassword(), DB: 0, }) - ctx = context.Background() + return &database{ + connection: redisConnection, + }, nil } -func createEntry(code string) *redis.StatusCmd { - if connection == nil { - createConnection() - } - +func (d *database) CreateEntry(ctx context.Context, code string) error { log.Debug("Setting value in Redis...") - err := connection.Set(ctx, keyName, code, 0) - if err != nil { - log.Error(err) - } + status := d.connection.Set(ctx, keyName, code, 0) - return err + return status.Err() } -func readEntry() (string, bool) { - if connection == nil { - createConnection() - } - +func (d *database) ReadEntry(ctx context.Context) (string, error) { log.Debug("Getting value from Redis...") - stringValue, err := connection.Get(ctx, keyName).Result() - - if err != nil { - log.Error(err) - return stringValue, true - } - return stringValue, false + return d.connection.Get(ctx, keyName).Result() } func getAddress() string { diff --git a/cocopasty-backend/go.mod b/cocopasty-backend/go.mod index 8068be3..df4bce7 100644 --- a/cocopasty-backend/go.mod +++ b/cocopasty-backend/go.mod @@ -1,4 +1,4 @@ -module cocopasty-backend +module github.com/MasterEvariour/cocopasty/cocopasty-backend go 1.18 diff --git a/cocopasty-backend/main.go b/cocopasty-backend/main.go index 606f56f..5a8fc40 100644 --- a/cocopasty-backend/main.go +++ b/cocopasty-backend/main.go @@ -2,7 +2,6 @@ package main import ( "encoding/json" - "fmt" "net/http" "github.com/gorilla/mux" @@ -11,23 +10,35 @@ import ( ) type CodeSnippet struct { - Code string `json:Code` + Code string `json:"Code"` } +var databaseClient *database + func main() { setLogLevel() //Initialize router log.Info("Starting Cocopasty...") router := mux.NewRouter() + router.Use(LoggingMiddleware) + router.HandleFunc("/", handleGets).Methods("GET") router.HandleFunc("/", handlePosts).Methods("POST") corsHandler := cors.Default().Handler(router) + //Create database connection + var err error + databaseClient, err = CreateDatabaseClient() + + if err != nil { + panic(err) + } + //Start server log.Info("Starting web server...") - err := http.ListenAndServe(":8080", corsHandler) + err = http.ListenAndServe(":8080", corsHandler) if err != nil { log.Fatal(err) } @@ -35,7 +46,7 @@ func main() { } func handlePosts(w http.ResponseWriter, r *http.Request) { - log.Debug("Received POST-Request") + ctx := r.Context() contentType := r.Header.Get("Content-Type") if contentType != "application/json" { @@ -46,32 +57,31 @@ func handlePosts(w http.ResponseWriter, r *http.Request) { var newSnippet CodeSnippet - decoder := json.NewDecoder(r.Body) - err := decoder.Decode(&newSnippet) - + err := json.NewDecoder(r.Body).Decode(&newSnippet) if err != nil { - log.Debug("Invalid JSON, returning 400") - fmt.Print(err) + log.Error(err) w.WriteHeader(http.StatusBadRequest) return } - createEntry(newSnippet.Code) - - log.Debug("GET-Request successfull, returning 200") - w.WriteHeader(http.StatusOK) + err = databaseClient.CreateEntry(ctx, newSnippet.Code) + if err != nil { + log.Error(err) + w.WriteHeader(http.StatusInternalServerError) + return + } } func handleGets(w http.ResponseWriter, r *http.Request) { - log.Debug("Received GET-Request") + ctx := r.Context() w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) - value, err := readEntry() + value, err := databaseClient.ReadEntry(ctx) - if err { - log.Debug("GET-Request failure, returning 500") + if err != nil { + log.Error(err) w.WriteHeader(http.StatusInternalServerError) return } diff --git a/cocopasty-backend/middleware.go b/cocopasty-backend/middleware.go new file mode 100644 index 0000000..c4fd150 --- /dev/null +++ b/cocopasty-backend/middleware.go @@ -0,0 +1,16 @@ +package main + +import ( + "net/http" + + log "github.com/sirupsen/logrus" +) + +func LoggingMiddleware(next http.Handler) http.Handler { + return http.HandlerFunc( + func(w http.ResponseWriter, r *http.Request) { + log.Debugf("Incoming request:\nMethod: '%s'\nURI: '%s'", r.Method, r.RequestURI) + next.ServeHTTP(w, r) + }, + ) +} diff --git a/cocopasty-backend/utils.go b/cocopasty-backend/utils.go index ed56570..461e08b 100644 --- a/cocopasty-backend/utils.go +++ b/cocopasty-backend/utils.go @@ -7,13 +7,15 @@ import ( ) func setLogLevel() { + defer log.Info("Log level to ", log.GetLevel()) input := os.Getenv("LOG_LEVEL") parsedLevel, err := log.ParseLevel(input) - if err == nil { - log.SetLevel(parsedLevel) + if err != nil { + log.Error(err) + return } - log.Info("Log level to ", log.GetLevel()) + log.SetLevel(parsedLevel) } diff --git a/docker-compose-deploy.yml b/docker-compose-deploy.yml index 2d5f37f..c69d54c 100644 --- a/docker-compose-deploy.yml +++ b/docker-compose-deploy.yml @@ -7,7 +7,7 @@ services: VUE_APP_BACKEND_PORT: 8081 VUE_APP_BACKEND_HOST: "http://localhost" backend: - image: masterevarior/cocopasty-backend:1.1.0 + image: masterevarior/cocopasty-backend:1.2.0 ports: - "8081:8080" environment: