How does ServeHTTP work?

前端 未结 5 838
温柔的废话
温柔的废话 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:47

    Type declaration in this code for

    type foo int
    

    is implementing Handler interface. We can create struct or any type to implement ServeHTTP method. like

    type Foo struct{}
    func (m foo) ServeHTTP(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintln(w, "Some text")
    }
    

    For implementing Handler interface or any other interface It is been required to implement all methods declared in the interface on a type which is foo here.

    HandlerFunc is implementing ServeHttp method of Handler interface and hence can be passed to http.ListenAndServe as a handler. It can be used to create middlewares wrapping around ServeHttp.

    For more information on HanlderFunc use go doc in terminal

    godoc net/http HanlderFunc

提交回复
热议问题