Golang中的路由使用详解

2019-11-10 11:41:37丽君

之前有篇文章比较浅显的分析了一下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)
}

...

然后再修改一下调用方式。