You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
These are excerpts from the documentation for the ResponseWriter interface. For Write:
// If WriteHeader has not yet been called, Write calls
// WriteHeader(http.StatusOK) before writing the data.
For WriteHeader:
// If WriteHeader is not called explicitly, the first call to Write
// will trigger an implicit WriteHeader(http.StatusOK).
The code below never calls ResponseWriter.WriteHeader for simple requests. I had expected that the implementation of the ResponseWriter interface would follow it by calling out to the interface WriteHeader method instead of directly calling its internal writeHeader function.
package main
import (
"fmt""net/http"
)
funcmain() {
http.HandleFunc("/", func(w http.ResponseWriter, r*http.Request) {
fmt.Fprintln(w, "Hello World!")
})
http.ListenAndServe(":8080", Middleware(http.DefaultServeMux))
}
funcMiddleware(h http.Handler) http.Handler {
returnhttp.HandlerFunc(func(w http.ResponseWriter, r*http.Request) {
// Use a different ResponseWriter for this request...w2:=myResponseWriter{w}
h.ServeHTTP(w2, r)
})
}
typemyResponseWriterstruct {
http.ResponseWriter
}
func (wmyResponseWriter) WriteHeader(codeint) {
// This code is never called with the http.response implementation.w.ResponseWriter.WriteHeader(code)
fmt.Println("Yay, I wrote a header!")
}
Nevermind, I was thinking a bit oddly about this, that something else is causing WriteHeader to be called but if the concrete implementation does everything it can't know that it's been wrapped.
If someone else finds this issue because they were trying to do what I'm doing, I believe this is a valid base to start off a ResponseWriter wrapper from:
typeMyResponseWriterstruct {
http.ResponseWriterwroteHeaderbool
}
func (w*MyResponseWriter) Write(p []byte) (nint, errerror) {
if!w.wroteHeader {
w.WriteHeader(http.StatusOK)
}
returnw.ResponseWriter.Write(p)
}
func (w*MyResponseWriter) WriteHeader(codeint) {
w.ResponseWriter.WriteHeader(code)
// Check after in case there's error handling in the wrapped ResponseWriter.if!w.wroteHeader {
return
}
w.wroteHeader=true// Do other stuff here.
}
These are excerpts from the documentation for the
ResponseWriter
interface. ForWrite
:For
WriteHeader
:The code below never calls
ResponseWriter.WriteHeader
for simple requests. I had expected that the implementation of theResponseWriter
interface would follow it by calling out to the interfaceWriteHeader
method instead of directly calling its internalwriteHeader
function.I also put this code on the Go Playground.
Go version that I'm using:
The text was updated successfully, but these errors were encountered: