我正在嘗試使用 go-chi 開發一個 api 網關。我希望如果請求在查詢中包含“_always200=true”,我會將狀態代碼設為 200。 這是我嘗試過的: custom_response_writer.go:
type CustomResponseWriter struct { http.ResponseWriter Buf *bytes.Buffer StatusCode int WroteHeader bool } func NewCustomResponseWriter(w http.ResponseWriter) *CustomResponseWriter { return &CustomResponseWriter{ResponseWriter: w, Buf: new(bytes.Buffer)} } func (c *CustomResponseWriter) WriteHeader(code int) { c.StatusCode = code c.ResponseWriter.WriteHeader(code) } func (c *CustomResponseWriter) Write(b []byte) (int, error) { return c.Buf.Write(b) }
中介軟體:
func HeaderFilterMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { always200, _ := r.Context().Value(always200QueryKey).(bool) crw := NewCustomResponseWriter(w) next.ServeHTTP(crw, r) if always200 { crw.WriteHeader(http.StatusOK) } }) }
總是回傳404。有什麼辦法可以解決這個問題嗎?
程式碼中至少存在兩個問題。
always200, _ := r.Context().Value(always200QueryKey).(bool)
不是取得查詢參數的正確方法。我認為您應該使用 r.URL.Query().Get("_always200")
來讀取它,並將該值與字串 "true"
進行比較。
在 next.ServeHTTP(crw, r)
之後呼叫 crw.WriteHeader(http.StatusOK)
已經太晚了。當我測試程式碼時,它列印了此警告訊息:
http: superfluous response.WriteHeader call from main.(*CustomResponseWriter).WriteHeader
以下是更改回應狀態程式碼的修改範例:
<code>package main import ( "bytes" "net/http" "strings" "github.com/go-chi/chi/v5" ) type CustomResponseWriter struct { http.ResponseWriter Buf *bytes.Buffer OriginalStatusCode int WroteHeader bool always200 bool } func NewCustomResponseWriter(w http.ResponseWriter, always200 bool) *CustomResponseWriter { return &CustomResponseWriter{ ResponseWriter: w, Buf: new(bytes.Buffer), always200: always200, } } func (c *CustomResponseWriter) WriteHeader(code int) { c.OriginalStatusCode = code if c.always200 { code = http.StatusOK } c.ResponseWriter.WriteHeader(code) } func (c *CustomResponseWriter) Write(b []byte) (int, error) { return c.Buf.Write(b) } func HeaderFilterMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { always200 := r.URL.Query().Get("_always200") crw := NewCustomResponseWriter(w, strings.EqualFold(always200, "true")) next.ServeHTTP(crw, r) }) } func main() { r := chi.NewRouter() r.Use(HeaderFilterMiddleware) r.Get("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("welcome")) }) http.ListenAndServe(":3000", r) } </code>
以上是如何使用中介軟體更改http請求的回應代碼?的詳細內容。更多資訊請關注PHP中文網其他相關文章!