Handler, DefaultServeMux,HandlerFuncDefaultServeMuxpatternhandler首先我们需要一个能够保存客户端的请求的一个容器(路由)。
创建路由结构体
type CopyRouter struct {
router map[string]map[string]http.HandlerFunc
}
在这里我们创建了一个像DefaultServeMux的路由。
客户端请求存入路由
func (c *CopyRouter) HandleFunc(method, pattern string, handle http.HandlerFunc) {
if method == "" {
panic("Method can not be null!")
}
if pattern == "" {
panic("Pattern can not be null!")
}
if _, ok := c.router[method][pattern]; ok {
panic("Pattern Exists!")
}
if c.router == nil {
c.router = make(map[string]map[string]http.HandlerFunc)
}
if c.router[method] == nil {
c.router[method] = make(map[string]http.HandlerFunc)
}
c.router[method][pattern] = handle
}
ServeMux实现Handler接口
func (c *CopyRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if f, ok := c.router[r.Method][r.URL.String()]; ok {
f.ServeHTTP(w, r)
}
}
h.ServeHTTP(w, r),Handler获取一个路由
func NewRouter() *CopyRouter {
return new(CopyRouter)
}
到这里,我们自己定义的路由就完成了,我们来看看使用方法。
func sayHi(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w,"Hi")
}
func main() {
copyRouter := copyrouter.NewRouter()
copyRouter.HandleFunc("GET","/sayHi", sayHi)
log.Fatal(http.ListenAndServe("localhost:8080", copyRouter))
}
ServeMux现在再看看,我们的main函数里面的代码不是很美观,每一次都要写get或者post方法,那么我们能否提供一个比较美观的方式呢?可以,那么我们再封装一下。
func (c *CopyRouter) GET(pattern string, handler http.HandlerFunc){
c.HandleFunc("GET", pattern, handler)
}
func (c *CopyRouter) POST(pattern string, handler http.HandlerFunc){
c.HandleFunc("POST", pattern, handler)
}
...
然后再修改一下调用方式。
copyRouter.GET("/sayHi",sayHi)现在看起来是不是就美观很多了?是的,很多web框架也是这样,为什么用起来就感觉很流畅,因为这些大神们就是站在我们开发者的角度来考虑问题,提供了很方便的一些用法,封装的很完善。
ServeHTTPfunc (c *CopyRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if f, ok := c.router[r.Method][r.URL.String()]; ok {
func (handler http.Handler){
start := time.Now()
log.Printf(" 请求 [%s] 开始时间为 : %v\n", r.URL.String(), start)
f.ServeHTTP(w, r)
log.Printf(" 请求 [%s] 完成时间为 : %v\n", r.URL.String(), time.Since(start))
}(f)
}
}
这里我们又加入了一个记录请求时间的功能,所以在这个自定义的路由里面还可以做更多的事情。
map[string]map[string]http.HandlerFuncmap[string]map[string]http.HandlercopyRouter.GET("/sayHi",HandlerFunc(sayHi))在这里做一个强制转换即可,但是这样也不是很美观。
看到这里,我们应该对一个源码中的类型重点关注一下,那就是HandlerFunc。
type HandlerFunc func(ResponseWriter, *Request)
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
f(w, r)
}
这里HandlerFunc起到了一个适配器的作用,这是一个非常巧妙的设计,不得不说golang在接口这方面确实设计的很精妙。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。