Home > database >  What original type is passed in ServeHTTP's http.ResponseWriter interface?
What original type is passed in ServeHTTP's http.ResponseWriter interface?

Time:09-22

While studying net/http I actually wanted to know that how go returns http.Response to listener. From this answer, I found that http.Response type is passed to ServeHTTP, but that is not the case because on compilation below code throw error. Which means http.Response does not implement http.ResponseWriter interface. I am curious what is the type which implements http.ResponseWriter interface?

# command-line-arguments
./server1.go:9:20: http.Response.Header is a field, not a method
./server1.go:9:20: impossible type assertion:
        http.Response does not implement http.ResponseWriter (missing Header method)
func handler(resp http.ResponseWriter, req *http.Request){
    actualresp := resp.(http.Response) //https://tour.golang.org/methods/15
    resp.Write([]byte("Hello Web, from go"))
}
func main(){
    http.HandleFunc("/api", handler)
    http.ListenAndServe(":8000", nil)
}

CodePudding user response:

http.Response has the following methods only:

func (r *Response) Cookies() []*Cookie
func (r *Response) Location() (*url.URL, error)
func (r *Response) ProtoAtLeast(major, minor int) bool
func (r *Response) Write(w io.Writer) error

This does not implement the http.ResponseWriter interface which requires:

Header() Header
Write([]byte) (int, error)
WriteHeader(statusCode int)

So clearly http.Response cannot be used as a http.ResponseWriter.

Instead, and as the answer you linked to mentions, the non-exported http.response is used. You can find a description of the life of a write on the http server side in the code.

  • Related