我的第一个 stackoverflow 问题,所以请不要介意我对 stackoverflow 的天真和所问的问题,golang 的初学者。
我想知道这两个调用之间的区别以及对,,,Handle的Handler简单理解。HandleFuncHandlerFunc
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")
}
Run Code Online (Sandbox Code Playgroud)
我想...简单的了解一下Handle、Handler、HandleFunc、HandlerFunc。
Handler是一个可以响应HTTP请求并有ServeHTTP(ResponseWriter, *Request)方法的接口。http.Handle注册 aHandler来处理与给定 匹配的 HTTP 请求pattern。http.HandleFunc注册一个处理函数来处理与给定的pattern. 处理函数应采用以下形式func(ResponseWriter, *Request)。HandlerFunc是 形式的显式函数类型func(ResponseWriter, *Request)。HandlerFunc有一个ServeHTTP调用自身的方法。这允许您将函数转换为 aHandlerFunc并将其用作 a Handler。我想知道这两个电话之间的区别
http.Handle("/profile", Logger(profilefunc))
http.HandleFunc("/", HomeFunc)
Run Code Online (Sandbox Code Playgroud)
Logger是一个中间件的示例,它是一个接受 anhttp.Handler并返回另一个http.Handler包装原始处理程序的函数。调用时,此处理程序可能(或可能不)http.Handler在执行某些操作之前和/或之后调用嵌套的处理程序。所以第一行是说用模式“/profile”注册中间件profileFunc Handler中的包装。Logger第二行是HomeFunc用“/”模式注册函数。