Skip to content

Commit

Permalink
Refactor server setup and remove redundant return statements
Browse files Browse the repository at this point in the history
- 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.
  • Loading branch information
sbshah97 committed Sep 1, 2024
1 parent c81a9e6 commit a1d46d9
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
11 changes: 10 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package main
import (
"net/http"
"strconv"
"time"

"log/slog"

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

}
7 changes: 3 additions & 4 deletions pkg/handlers/users.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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)
}
}

0 comments on commit a1d46d9

Please sign in to comment.