Skip to content

Commit

Permalink
Merge pull request #7 from MasterEvarior/6-code-improvements
Browse files Browse the repository at this point in the history
Improved various things
  • Loading branch information
MasterEvarior authored May 23, 2022
2 parents f3c841a + bd97711 commit ab8ce82
Show file tree
Hide file tree
Showing 6 changed files with 64 additions and 49 deletions.
41 changes: 14 additions & 27 deletions cocopasty-backend/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion cocopasty-backend/go.mod
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module cocopasty-backend
module github.com/MasterEvariour/cocopasty/cocopasty-backend

go 1.18

Expand Down
44 changes: 27 additions & 17 deletions cocopasty-backend/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package main

import (
"encoding/json"
"fmt"
"net/http"

"github.com/gorilla/mux"
Expand All @@ -11,31 +10,43 @@ 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)
}
log.Info("Cocopasty is started and ready!")
}

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" {
Expand All @@ -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
}
Expand Down
16 changes: 16 additions & 0 deletions cocopasty-backend/middleware.go
Original file line number Diff line number Diff line change
@@ -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)
},
)
}
8 changes: 5 additions & 3 deletions cocopasty-backend/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
2 changes: 1 addition & 1 deletion docker-compose-deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down

0 comments on commit ab8ce82

Please sign in to comment.