我的第一个 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")
}
我想...简单的了解一下Handle、Handler、HandleFunc、HandlerFunc。
-
Handler
是一个可以响应HTTP请求的接口,并且有一个ServeHTTP(ResponseWriter, *Request)
method.
-
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
是一个例子中间件 http://www.alexedwards.net/blog/making-and-using-middleware,这是一个需要一个函数http.Handler
它返回另一个http.Handler
包装原始处理程序。调用时,此处理程序可能(或可能不)调用嵌套的http.Handler
在执行某些操作之前和/或之后。所以第一行是说注册profileFunc
Handler
包裹在Logger
具有“/profile”模式的中间件。第二行是说注册HomeFunc
具有“/”模式的函数。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)