How does ServeHTTP work?

前端 未结 5 830
温柔的废话
温柔的废话 2020-12-14 03:55

I am studying web development in Golang (Beginner) I came across some code I played around with and I\'m not too sure why it works, I looked through the library source code

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-14 04:52

    Go's HTTP server takes in an address to listen on, and a handler. Internally, it creates a TCP listener to accept connections on the given address, and whenever a request comes in, it:

    1. Parses the raw HTTP request (path, headers, etc) into a http.Request
    2. Creates a http.ResponseWriter for sending the response
    3. Invokes the handler by calling its ServeHTTP method, passing in the Request and ResponseWriter

    The handler can be anything that satisfies the Handler interface, which your foo type does:

    type Handler interface {
        ServeHTTP(ResponseWriter, *Request)
    }
    

    The standard library also includes some conveniences, like HandlerFunc (which allows you to pass any func(ResponseWriter, *Request) and use it as a Handler) and ServeMux, which allows you to register many Handlers and choose which one handles which request based on the incoming request path.

提交回复
热议问题