Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: implement response controller for logging middleware #101

Merged
merged 2 commits into from
Nov 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 0 additions & 20 deletions internal/server/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,26 +28,6 @@ type middlewareContext struct {
jwtSecret []byte
}

// The statusRecorder struct wraps the http.ResponseWriter struct, and extracts the status
// code of the response writer for the middleware to read
type statusRecorder struct {
http.ResponseWriter
statusCode int
}

// newResponseWriter returns a new ResponseWriterCloner struct
// it returns http.StatusOK by default because the http.ResponseWriter defaults to that header
// if the WriteHeader() function is never called.
func newResponseWriter(w http.ResponseWriter) *statusRecorder {
return &statusRecorder{w, http.StatusOK}
}

// WriteHeader overrides the ResponseWriter method to duplicate the status code into the wrapper struct
func (rwc *statusRecorder) WriteHeader(code int) {
rwc.statusCode = code
rwc.ResponseWriter.WriteHeader(code)
}

// createMiddlewareStack chains the given middleware functions to wrap the api.
// Each middleware functions calls next.ServeHTTP in order to resume the chain of execution.
// The order the middleware functions are given to createMiddlewareStack matters.
Expand Down
30 changes: 30 additions & 0 deletions internal/server/response_controller.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package server

import "net/http"

type responseWriter struct {
http.ResponseWriter
statusCode int
}

func newResponseWriter(w http.ResponseWriter) *responseWriter {
return &responseWriter{
ResponseWriter: w,
statusCode: 0,
}
}

func (mw *responseWriter) WriteHeader(statusCode int) {
mw.ResponseWriter.WriteHeader(statusCode)
if mw.statusCode == 0 {
mw.statusCode = statusCode
}
}

func (mw *responseWriter) Write(b []byte) (int, error) {
return mw.ResponseWriter.Write(b)
}

func (mw *responseWriter) Unwrap() http.ResponseWriter {
return mw.ResponseWriter
}
Loading