Difference between http.Handle and http.HandleFunc?

后端 未结 3 573
陌清茗
陌清茗 2020-12-07 15:19

The Go docs have the following example for the http package:

http.Handle(\"/foo\", fooHandler)
http.HandleFunc(\"/bar\", func(w http.ResponseWriter, r *http.         


        
3条回答
  •  难免孤独
    2020-12-07 15:58

    No It's Different. Let's Examine

    func Handle(pattern string, handler Handler) {
        DefaultServeMux.Handle(pattern, handler) 
    }
    

    handle expects us to pass a Handler. Handler is an interface

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

    if any type implements ServeHTTP(ResponseWriter, *Request) for example: myCustomHandler then we can pass it like Handle(pattern string, myCustomHandler).

    In the second scenario:

    HandleFunc(pattern string, func(w ResponseWriter, r *Request) {
        // do some stuff
    }
    

    HandleFunc expects a function where Handle expects a Handler interface.

    So, if you just want to pass a function then you can use http.HandleFunc(..). Like @David showed that behind the scenes it implements Handler interface by calling ServeHTTP.

    type HandlerFunc func(ResponseWriter, *Request)
    
    // ServeHTTP calls f(w, r).
    func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
        f(w, r)
    }
    

提交回复
热议问题