我的第一个 stackoverflow 问题,所以请不要介意我对 stackoverflow 的天真和所问的问题,golang 的初学者。
我想知道这两个调用之间的区别以及对,,,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")
}
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
用“/”模式注册函数。