Home > other >  ResponseWriter interface in Go net/http package
ResponseWriter interface in Go net/http package

Time:08-19

I have two questions about the ResponseWriter interface in net/http package. Here is my code

package main

import (
    "fmt"
    "net/http"
    "os"
)

type handler struct{}

func (h *handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
    fmt.Fprintf(w, "Method: %v\n", req.Method)
    fmt.Fprintf(w, "URL: %v\n", req.URL)
    fmt.Fprintf(w, "Protocol: %v\n", req.Proto)

    fmt.Fprintf(os.Stdout, "Header: %v\n", w.Header())
}

func main() {
    http.ListenAndServe(":8080", &handler{})
}

and to check the code I used curl in cmd. Below you can see the curl command and its result.

C:\Users>curl -i -X GET localhost:8080
HTTP/1.1 200 OK
Date: Fri, 19 Aug 2022 03:47:21 GMT
Content-Length: 38
Content-Type: text/plain; charset=utf-8

Method: GET
URL: /
Protocol: HTTP/1.1

Since http.ResponseWriter is only an interface and I have not implemented any concrete type in my program to satisfy this interface, why is my code working? As far as I understood there is no implementation for interface methods. So how do I get a correct response from curl?

Also, as you can see in the output of curl, I am receiving an http response with a header. However, output of fmt.Fprintf(os.Stdout, "Header: %v\n", w.Header()) is Header: map[]. If I am right, Header method for http.ResponseWriter must return the response header which is not empty based on the curl output. So why does Fprintf return an empty map?

Thank you for your help.

CodePudding user response:

Since http.ResponseWriter is only an interface and I have not implemented any concrete type in my program to satisfy this interface, why is my code working?

You haven't; the standard library has (namely, the private http.response and http.http2responsewriter types). The http server passes an instance of one of those types in to your handler. You don't need to know what it is; you just know that whatever you get, it will implement the ResponseWriter methods.

So why does Fprintf return an empty map?

Because the map is empty, because you didn't set any headers. Some servers (like Date and Content-Type) can be set automatically by the server if you don't set them yourself, but this is happening after the point where you are printing.

  • Related