Skip to content

Commit

Permalink
404/405 responses fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
denpeshkov committed Dec 30, 2023
1 parent f7de27e commit ca01fdc
Showing 1 changed file with 12 additions and 14 deletions.
26 changes: 12 additions & 14 deletions internal/http/server.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package http

import (
"encoding/json"
"log/slog"
"net/http"
"os"
Expand Down Expand Up @@ -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
}

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

Expand Down

0 comments on commit ca01fdc

Please sign in to comment.