当前位置 博文首页 > Golang中的路由使用详解

    Golang中的路由使用详解

    作者:达闻西 时间:2021-06-26 17:49

    之前有篇文章比较浅显的分析了一下golang的服务器如何实现,还有Handler, DefaultServeMux,HandlerFunc的用处。

    我们现在已经明白了DefaultServeMux就是存放patternhandler的地方,我们称其为路由,那么我们可能会想,既然golang能够实现这个路由,我们能否也模仿一个呢?

    首先我们需要一个能够保存客户端的请求的一个容器(路由)。

    创建路由结构体

    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将每一个URL所对应的handler保存起来。

    实现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)
      }
    }
    

    在这里为什么要实现这个Handler接口,因为我们发现在ListenAndServe方法中,最后会调用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))
    }
    
    

    这样就完成了一个高仿版的自定义路由,是不是和golang提供给我们的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框架也是这样,为什么用起来就感觉很流畅,因为这些大神们就是站在我们开发者的角度来考虑问题,提供了很方便的一些用法,封装的很完善。

    再考虑一下,我们这个自定义的路由还能做些什么,如果我们要记录每一次的访问请求,该如何处理呢?也很简单,我们只需要将逻辑写在ServeHTTP方法中就可以了,稍微修改一下我们的代码。

    func (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)
      }
    }
    

    这里我们又加入了一个记录请求时间的功能,所以在这个自定义的路由里面还可以做更多的事情。

    还有一点,就是我们在定义这个路由结构体的时候,能否将这个类型修改为Handler呢?也就是将这个类型map[string]map[string]http.HandlerFunc修改为map[string]map[string]http.Handler,是可以的,但是我们在调用的时候就需要在main方法里面做一下修改。

    copyRouter.GET("/sayHi",HandlerFunc(sayHi))

    在这里做一个强制转换即可,但是这样也不是很美观。

    看到这里,我们应该对一个源码中的类型重点关注一下,那就是HandlerFunc。

    type HandlerFunc func(ResponseWriter, *Request)
    
    func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
      f(w, r)
    }
    
    

    这里HandlerFunc起到了一个适配器的作用,这是一个非常巧妙的设计,不得不说golang在接口这方面确实设计的很精妙。

    js
    下一篇:没有了