From ca01fdc8ea9090e15dcb4aa87e84a9afcbe68a6a Mon Sep 17 00:00:00 2001 From: Denis Peshkov Date: Sat, 30 Dec 2023 10:22:59 +0400 Subject: [PATCH] 404/405 responses fixes --- internal/http/server.go | 26 ++++++++++++-------------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/internal/http/server.go b/internal/http/server.go index 3435233..ad7d460 100644 --- a/internal/http/server.go +++ b/internal/http/server.go @@ -1,6 +1,7 @@ package http import ( + "encoding/json" "log/slog" "net/http" "os" @@ -53,8 +54,6 @@ func (s *Server) Start() error { // hijackResponseWriter records status of the HTTP response. type hijackResponseWriter struct { http.ResponseWriter - r *http.Request - s *Server status int } @@ -63,26 +62,25 @@ func (w *hijackResponseWriter) WriteHeader(statusCode int) { w.ResponseWriter.WriteHeader(statusCode) } -func (w *hijackResponseWriter) Write(data []byte) (int, error) { +func (w *hijackResponseWriter) Write(data []byte) (n int, err error) { switch w.status { case http.StatusNotFound: - return Error(w.s, w.ResponseWriter, w.r, http.StatusNotFound, ErrorResponse{Msg: "Not Found", err: nil}) + data, err = json.Marshal(ErrorResponse{Msg: http.StatusText(http.StatusNotFound), err: nil}) + if err != nil { + return 0, err + } case http.StatusMethodNotAllowed: - return Error(w.s, w.ResponseWriter, w.r, http.StatusMethodNotAllowed, ErrorResponse{Msg: "Method Not Allowed", err: nil}) - default: - return w.ResponseWriter.Write(data) + data, err = json.Marshal(ErrorResponse{Msg: http.StatusText(http.StatusMethodNotAllowed), err: nil}) + if err != nil { + return 0, err + } } + return w.ResponseWriter.Write(data) } // ServeHTTP handles an HTTP request. func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { - sR := &hijackResponseWriter{ - ResponseWriter: w, - r: r, - s: s, - status: http.StatusOK, - } - + sR := &hijackResponseWriter{ResponseWriter: w, status: http.StatusOK} s.router.ServeHTTP(sR, r) }