Skip to content

Commit

Permalink
DiceDB#21: Added slog instead of log | moved pkg/util/cmds to /util/cmds
Browse files Browse the repository at this point in the history
  • Loading branch information
rishavvajpayee committed Oct 4, 2024
1 parent 5123dde commit 37c3c3c
Show file tree
Hide file tree
Showing 7 changed files with 20 additions and 27 deletions.
2 changes: 1 addition & 1 deletion internal/db/dicedb.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
"log/slog"
"os"
"server/config"
"server/pkg/util/cmds"
"server/util/cmds"
"time"

dicedb "github.com/dicedb/go-dice"
Expand Down
18 changes: 9 additions & 9 deletions internal/server/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@ import (
"context"
"encoding/json"
"errors"
"log"
"log/slog"
"net/http"
"server/internal/middleware"
"strings"
"sync"
"time"

"server/internal/db"
util "server/pkg/util"
util "server/util"
)

type HTTPServer struct {
Expand All @@ -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)
Expand Down Expand Up @@ -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())
Expand All @@ -116,15 +116,15 @@ 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
}

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
}
Expand Down
2 changes: 1 addition & 1 deletion internal/tests/integration/ratelimiter_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
2 changes: 1 addition & 1 deletion internal/tests/stress/ratelimiter_stress_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"net/http"
"net/http/httptest"
"server/config"
util "server/pkg/util"
util "server/util"
"sync"
"testing"
"time"
Expand Down
6 changes: 3 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package main

import (
"context"
"log"
"log/slog"
"net/http"
"server/config"
"server/internal/db"
Expand All @@ -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
Expand All @@ -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))
}
}
File renamed without changes.
17 changes: 5 additions & 12 deletions pkg/util/helpers.go → util/helpers.go
Original file line number Diff line number Diff line change
@@ -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"
)

Expand Down Expand Up @@ -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()
Expand All @@ -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)
Expand All @@ -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 {
Expand All @@ -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 {
Expand All @@ -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 {
Expand All @@ -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 {
Expand All @@ -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))
}
}

Expand Down

0 comments on commit 37c3c3c

Please sign in to comment.