From a1d46d98a3e82a47a3953d6ed509e771cb66ba21 Mon Sep 17 00:00:00 2001 From: sbshah97 Date: Sun, 1 Sep 2024 12:46:29 +0100 Subject: [PATCH] Refactor server setup and remove redundant return statements - Updated main.go to configure HTTP server with timeouts for better performance and security. - Removed redundant return statements from CreateUsers and FetchUsers handlers in users.go to clean up the code. --- main.go | 11 ++++++++++- pkg/handlers/users.go | 7 +++---- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/main.go b/main.go index de49870..a8dadcf 100644 --- a/main.go +++ b/main.go @@ -3,6 +3,7 @@ package main import ( "net/http" "strconv" + "time" "log/slog" @@ -45,8 +46,16 @@ func main() { http.Handle("/", r) slog.Info("Listening on http://localhost:" + strconv.Itoa(port)) - err = http.ListenAndServe(":"+strconv.Itoa(port), nil) + server := &http.Server{ + Addr: ":" + strconv.Itoa(port), + Handler: r, + ReadTimeout: 5 * time.Second, + WriteTimeout: 10 * time.Second, + IdleTimeout: 15 * time.Second, + } + err = server.ListenAndServe() if err != nil { slog.Error("failed to listen", "error", err) } + } diff --git a/pkg/handlers/users.go b/pkg/handlers/users.go index 4c364e8..6c228d0 100644 --- a/pkg/handlers/users.go +++ b/pkg/handlers/users.go @@ -47,8 +47,6 @@ func (h handler) CreateUsers(w http.ResponseWriter, r *http.Request) { slog.Error("Error in encoding response", "error", err) http.Error(w, fmt.Sprintf("Error in encoding response: %+v", err.Error()), http.StatusInternalServerError) } - return - } func (h handler) FetchUsers(w http.ResponseWriter, r *http.Request) { @@ -78,6 +76,7 @@ func (h handler) FetchUsers(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", "application/json") - w.Write(jsonObject) - return + if _, err := w.Write(jsonObject); err != nil { + slog.Error("Error writing response", "error", err) + } }