Golang Standard Library Middleware

My first question is about using stackoverflow, so please go over my naivety about stackoverflow and ask a question new to golang.

I would like to know the difference between the two calls, as well as a simple understanding of Handle, Handler, HandleFunc, HandlerFunc.

http.Handle ("/ profile", Logger (profilefunc))
http.HandleFunc ("/", HomeFunc)

func main() {            
   fmt.Println("Starting the server.")

   profilefunc := http.HandlerFunc(ProfileFunc)

   http.Handle("/profile", Logger(profilefunc))
   http.HandleFunc("/", HomeFunc)

   http.ListenAndServe("0.0.0.0:8081", nil)
}

func Logger(h http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){
        log.Println("Before serving request")
        h.ServeHTTP(w, r)
        log.Println("After serving request")
    })
}

func ProfileFunc(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "You are on the profile page.")
}

func HomeFunc(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello Imran Pochi")
}
+4
source share
2 answers

I would like ... a simple understanding of Handle, Handler, HandleFunc, HandlerFunc.

  • Handleris an interface that can respond to an HTTP request and has a method ServeHTTP(ResponseWriter, *Request).
  • http.Handle Handler HTTP-, pattern.
  • http.HandleFunc HTTP-, pattern. func(ResponseWriter, *Request).
  • HandlerFunc - func(ResponseWriter, *Request). HandlerFunc ServeHTTP, . HandlerFunc Handler.

http.Handle("/profile", Logger(profilefunc))
http.HandleFunc("/", HomeFunc)

Logger middleware, , http.Handler http.Handler, . ( ) http.Handler / . , , profileFunc Handler, Logger /. , HomeFunc "/".

+1

, Go:

  • - , HTTP-. , , , ServeHTTP(). ServeHTTP() .

  • Handle() , ServeHTTP(). , , /, .

  • HandlerFunc - , ServeHTTP(). HandlerFunc Go HandlerFunc. HandlerFunc Handle() , . , HandlerFunc , .

  • HandleFunc() , . HandleFunc , , Handle().

:

  func handlerName(wr http.ResponseWriter, req *http.Request)
+2

Source: https://habr.com/ru/post/1677684/


All Articles