func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) 这个是模式匹配,对应处理函数。 func Handle(pattern string, handler Handler) 这个是干嘛用的呢?
有疑问加站长微信联系(非本文作者)

func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) 这个是模式匹配,对应处理函数。 func Handle(pattern string, handler Handler) 这个是干嘛用的呢?
有疑问加站长微信联系(非本文作者)
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
`单行代码`
Handler是一个接口。
而HandleFunc和Handle都是调用DefaultServeMux对应的方法,而DefaultServeMux是ServeMux的实例,ServeMux实现了Handler接口。事实上,HandleFunc最终还是会调用Handle方法。代码如下:
明白了吧?
大部分时候用HandleFunc()即可,方便(因为接收func函数);而如果想自己实现Handler接口,则可以使用Handle()
还不是很明白,handle()怎么用,能否给个例子?实现handlefun("/hello",hello)的功能
比如 本站对于静态资源的处理方式:
这里的
http.FileServer
就返回一个Handler实例,net/http
包中类似的还有package main import ( "fmt" "net/http" )
type AppHandler struct { appName string }
func(index AppHandler) ServeHTTP(w http.ResponseWriter, r http.Request) { fmt.Fprintf(w, "hello, %s!", index.appName) }
func main() { index := new(AppHandler) index.appName = "sample app" http.Handle("/", index) http.ListenAndServe(":8080", nil) }