From 37c3c3ca20c22b109810ecb4855126190d5508b0 Mon Sep 17 00:00:00 2001 From: rishavvajpayee Date: Sat, 5 Oct 2024 00:18:10 +0530 Subject: [PATCH] #21: Added slog instead of log | moved pkg/util/cmds to /util/cmds --- internal/db/dicedb.go | 2 +- internal/server/http.go | 18 +++++++++--------- .../ratelimiter_integration_test.go | 2 +- .../tests/stress/ratelimiter_stress_test.go | 2 +- main.go | 6 +++--- {pkg/util => util}/cmds/cmds.go | 0 {pkg/util => util}/helpers.go | 17 +++++------------ 7 files changed, 20 insertions(+), 27 deletions(-) rename {pkg/util => util}/cmds/cmds.go (100%) rename {pkg/util => util}/helpers.go (86%) diff --git a/internal/db/dicedb.go b/internal/db/dicedb.go index f082106..1701cf6 100644 --- a/internal/db/dicedb.go +++ b/internal/db/dicedb.go @@ -11,7 +11,7 @@ import ( "log/slog" "os" "server/config" - "server/pkg/util/cmds" + "server/util/cmds" "time" dicedb "github.com/dicedb/go-dice" diff --git a/internal/server/http.go b/internal/server/http.go index 7ec18b2..9b12ec3 100644 --- a/internal/server/http.go +++ b/internal/server/http.go @@ -4,7 +4,7 @@ import ( "context" "encoding/json" "errors" - "log" + "log/slog" "net/http" "server/internal/middleware" "strings" @@ -12,7 +12,7 @@ import ( "time" "server/internal/db" - util "server/pkg/util" + util "server/util" ) type HTTPServer struct { @@ -39,7 +39,7 @@ func errorResponse(response string) string { errorMessage := map[string]string{"error": response} jsonResponse, err := json.Marshal(errorMessage) if err != nil { - log.Printf("Error marshaling response: %v", err) + slog.Error("Error marshaling response: %v", slog.Any("err", err)) return `{"error": "internal server error"}` } return string(jsonResponse) @@ -78,20 +78,20 @@ func (s *HTTPServer) Run(ctx context.Context) error { wg.Add(1) go func() { defer wg.Done() - log.Printf("starting server at %s\n", s.httpServer.Addr) + slog.Info("starting server at", slog.String("addr", s.httpServer.Addr)) if err := s.httpServer.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { - log.Fatalf("http server error: %v", err) + slog.Error("http server error: %v", slog.Any("err", err)) } }() <-ctx.Done() - log.Println("shutting down server...") + slog.Info("shutting down server...") return s.Shutdown() } func (s *HTTPServer) Shutdown() error { if err := s.DiceClient.Client.Close(); err != nil { - log.Printf("failed to close dicedb client: %v", err) + slog.Error("failed to close dicedb client: %v", slog.Any("err", err)) } return s.httpServer.Shutdown(context.Background()) @@ -116,7 +116,7 @@ func (s *HTTPServer) CliHandler(w http.ResponseWriter, r *http.Request) { respStr, ok := resp.(string) if !ok { - log.Println("error: response is not a string", "error", err) + slog.Error("error: response is not a string", "error", slog.Any("err", err)) http.Error(w, errorResponse("internal Server Error"), http.StatusInternalServerError) return } @@ -124,7 +124,7 @@ func (s *HTTPServer) CliHandler(w http.ResponseWriter, r *http.Request) { httpResponse := HTTPResponse{Data: respStr} responseJSON, err := json.Marshal(httpResponse) if err != nil { - log.Println("error marshaling response to json", "error", err) + slog.Error("error marshaling response to json", "error", slog.Any("err", err)) http.Error(w, errorResponse("internal server error"), http.StatusInternalServerError) return } diff --git a/internal/tests/integration/ratelimiter_integration_test.go b/internal/tests/integration/ratelimiter_integration_test.go index 6de1b8e..7faca79 100644 --- a/internal/tests/integration/ratelimiter_integration_test.go +++ b/internal/tests/integration/ratelimiter_integration_test.go @@ -4,7 +4,7 @@ import ( "net/http" "net/http/httptest" config "server/config" - util "server/pkg/util" + util "server/util" "testing" "github.com/stretchr/testify/require" diff --git a/internal/tests/stress/ratelimiter_stress_test.go b/internal/tests/stress/ratelimiter_stress_test.go index b95b7c2..14d83e2 100644 --- a/internal/tests/stress/ratelimiter_stress_test.go +++ b/internal/tests/stress/ratelimiter_stress_test.go @@ -4,7 +4,7 @@ import ( "net/http" "net/http/httptest" "server/config" - util "server/pkg/util" + util "server/util" "sync" "testing" "time" diff --git a/main.go b/main.go index 6b37cde..b01de76 100644 --- a/main.go +++ b/main.go @@ -2,7 +2,7 @@ package main import ( "context" - "log" + "log/slog" "net/http" "server/config" "server/internal/db" @@ -13,7 +13,7 @@ func main() { configValue := config.LoadConfig() diceClient, err := db.InitDiceClient(configValue) if err != nil { - log.Fatalf("Failed to initialize DiceDB client: %v", err) + slog.Error("Failed to initialize DiceDB client: %v", slog.Any("err", err)) } // Create mux and register routes @@ -29,6 +29,6 @@ func main() { // Run the HTTP Server if err := httpServer.Run(ctx); err != nil { - log.Printf("server failed: %v\n", err) + slog.Error("server failed: %v\n", slog.Any("err", err)) } } diff --git a/pkg/util/cmds/cmds.go b/util/cmds/cmds.go similarity index 100% rename from pkg/util/cmds/cmds.go rename to util/cmds/cmds.go diff --git a/pkg/util/helpers.go b/util/helpers.go similarity index 86% rename from pkg/util/helpers.go rename to util/helpers.go index 48980b5..20b3c2b 100644 --- a/pkg/util/helpers.go +++ b/util/helpers.go @@ -1,16 +1,16 @@ -package helpers +package utils import ( "encoding/json" "errors" "fmt" "io" - "log" + "log/slog" "net/http" "net/http/httptest" "server/internal/middleware" db "server/internal/tests/dbmocks" - cmds "server/pkg/util/cmds" + cmds "server/util/cmds" "strings" ) @@ -57,13 +57,11 @@ func ParseHTTPRequest(r *http.Request) (*cmds.CommandRequest, error) { }, nil } -// extractCommand retrieves and formats the command from the URL path func extractCommand(path string) string { - command := strings.TrimPrefix(path, "/cli/") + command := strings.TrimPrefix(path, "/shell/exec/") return strings.ToUpper(command) } -// extractArgsFromRequest extracts arguments from the request's URL query and body func extractArgsFromRequest(r *http.Request, command string) ([]string, error) { var args []string queryParams := r.URL.Query() @@ -84,7 +82,6 @@ func extractArgsFromRequest(r *http.Request, command string) ([]string, error) { return args, nil } -// parseRequestBody parses the body of the request and extracts arguments from JSON content func parseRequestBody(body io.ReadCloser) ([]string, error) { var args []string bodyContent, err := io.ReadAll(body) @@ -111,7 +108,6 @@ func parseRequestBody(body io.ReadCloser) ([]string, error) { return args, nil } -// extractPriorityArgs extracts arguments for priority keys from the JSON body func extractPriorityArgs(jsonBody map[string]interface{}) []string { var args []string for _, key := range priorityKeys { @@ -130,7 +126,6 @@ func extractPriorityArgs(jsonBody map[string]interface{}) []string { return args } -// extractRemainingArgs processes any remaining non-priority arguments in the JSON body func extractRemainingArgs(jsonBody map[string]interface{}) []string { var args []string for key, val := range jsonBody { @@ -150,7 +145,6 @@ func extractRemainingArgs(jsonBody map[string]interface{}) []string { return args } -// convertListToStrings converts a list of interface{} to a list of strings func convertListToStrings(list []interface{}) []string { var result []string for _, v := range list { @@ -159,7 +153,6 @@ func convertListToStrings(list []interface{}) []string { return result } -// convertMapToStrings converts a map of key-value pairs to a flat list of strings func convertMapToStrings(m map[string]interface{}) []string { var result []string for k, v := range m { @@ -181,7 +174,7 @@ func JSONResponse(w http.ResponseWriter, status int, data interface{}) { func MockHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) if _, err := w.Write([]byte("OK")); err != nil { - log.Fatalf("Failed to write response: %v", err) + slog.Error("Failed to write response: %v", slog.Any("err", err)) } }