go-zero 单体应用框架学习—4 监听端口

自己根据go-zero单体框架实现的一个精简版框架https://github.com/wanmei002/go-zero-learn, 新手直接看go-zero 框架可能会绕,看这个好理解

框架运行起来

先说下思路:

  1. 注册必要的中间件
  2. 给每个路由处理函数用中间件处理
  3. 给路由生成字典树
  4. 开始监听端口

启动入口

入口函数 server.Start() ,实际上运行的是 Server.opts.start。

go-zero/rest/engine.go 文件中的 bindRoute 方法, 这个里面注册了中间件,
并对路由处理函数用中间件处理。中间件原理请看这篇文章

 ```go 
 func (c Chain) Then(h http.Handler) http.Handler {
    if h == nil {
        h = http.DefaultServeMux
    }
 
    for i := range c.constructors {
        h = c.constructors[len(c.constructors)-1-i](h)// 倒序运行中间件
    }
 
    return h
 }
 ```

和开始生成路由字典树,具体文章看这里go-zero 单体应用框架学习—3 路由生成字典树

开始监听端口:

func (s *engine) StartWithRouter(router httpx.Router) error {
	if err := s.bindRoutes(router); err != nil {
		return err
	}

	if len(s.conf.CertFile) == 0 && len(s.conf.KeyFile) == 0 {
		return internal.StartHttp(s.conf.Host, s.conf.Port, router) // http
	}

	return internal.StartHttps(s.conf.Host, s.conf.Port, s.conf.CertFile, s.conf.KeyFile, router)// https
}