扫码订阅《 》或入驻星球,即可阅读文章!

GOLANG ROADMAP

阅读模式

  • 沉浸
  • 自动
  • 日常
首页
Go学习
  • Go学院

    • Go小课
    • Go小考
    • Go实战
    • 精品课
  • Go宝典

    • 在线宝典
    • B站精选
    • 推荐图书
    • 精品博文
  • Go开源

    • Go仓库
    • Go月刊
  • Go下载

    • 视频资源
    • 文档资源
Go求职
  • 求职服务

    • 内推互助
    • 求职助力
  • 求职刷题

    • 企业题库
    • 面试宝典
    • 求职面经
Go友会
  • 城市
  • 校园
推广返利 🤑
实验区
  • Go周边
消息
更多
  • 用户中心

    • 我的信息
    • 推广返利
  • 玩转星球

    • 星球介绍
    • 角色体系
    • 星主权益
  • 支持与服务

    • 联系星主
    • 成长记录
    • 常见问题
    • 吐槽专区
  • 合作交流

    • 渠道合作
    • 课程入驻
    • 友情链接
author-avatar

GOLANG ROADMAP


首页
Go学习
  • Go学院

    • Go小课
    • Go小考
    • Go实战
    • 精品课
  • Go宝典

    • 在线宝典
    • B站精选
    • 推荐图书
    • 精品博文
  • Go开源

    • Go仓库
    • Go月刊
  • Go下载

    • 视频资源
    • 文档资源
Go求职
  • 求职服务

    • 内推互助
    • 求职助力
  • 求职刷题

    • 企业题库
    • 面试宝典
    • 求职面经
Go友会
  • 城市
  • 校园
推广返利 🤑
实验区
  • Go周边
消息
更多
  • 用户中心

    • 我的信息
    • 推广返利
  • 玩转星球

    • 星球介绍
    • 角色体系
    • 星主权益
  • 支持与服务

    • 联系星主
    • 成长记录
    • 常见问题
    • 吐槽专区
  • 合作交流

    • 渠道合作
    • 课程入驻
    • 友情链接
  • Go语言Web编程

    • 课程介绍
  • Web基础

  • 表单

  • 访问数据库

  • session和数据存储

  • 文本处理

  • Web服务

  • 安全与加密

  • 国际化和本地化

  • 错误处理,调试和测试

  • 部署与维护

  • 如何设计一个Web框架

    • 第1节:如何设计一个Web框架
    • 第2节:项目规划
    • 第3节:自定义路由器设计
    • 第4节:controller设计
    • 第5节:日志和配置设计
    • 第6节:实现博客的增删改
    • 第7节:小结
  • 扩展Web框架

扫码订阅《 》或入驻星球,即可阅读文章!

第3节:自定义路由器设计


ASTA谢

# HTTP 路由

HTTP 路由组件负责将 HTTP 请求交到对应的函数处理 (或者是一个 struct 的方法),如前面小节所描述的结构图,路由在框架中相当于一个事件处理器,而这个事件包括:

  • 用户请求的路径 (path) (例如: /user/123,/article/123),当然还有查询串信息 (例如 ?id=11)
  • HTTP的请求方法 (method) (GET、POST、PUT、DELETE、PATCH 等)

路由器就是根据用户请求的事件信息转发到相应的处理函数 (控制层)。

# 默认的路由实现

在 3.4 小节有过介绍 Go 的 http 包的详解,里面介绍了 Go 的 http 包如何设计和实现路由,这里继续以一个例子来说明:

func fooHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
}

http.HandleFunc("/foo", fooHandler)

http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
})

log.Fatal(http.ListenAndServe(":8080", nil))

1
2
3
4
5
6
7
8
9
10
11
12

上面的例子调用了 http 默认的 DefaultServeMux 来添加路由,需要提供两个参数,第一个参数是希望用户访问此资源的 URL 路径(保存在 r.URL.Path),第二参数是即将要执行的函数,以提供用户访问的资源。路由的思路主要集中在两点:

  • 添加路由信息
  • 根据用户请求转发到要执行的函数

Go 默认的路由添加是通过函数 http.Handle 和 http.HandleFunc 等来添加,底层都是调用了 DefaultServeMux.Handle(pattern string, handler Handler), 这个函数会把路由信息存储在一个 map 信息中 map[string]muxEntry,这就解决了上面说的第一点。

Go 监听端口,然后接收到 tcp 连接会扔给 Handler 来处理,上面的例子默认 nil 即为 http.DefaultServeMux,通过 DefaultServeMux.ServeHTTP 函数来进行调度,遍历之前存储的 map 路由信息,和用户访问的 URL 进行匹配,以查询对应注册的处理函数,这样就实现了上面所说的第二点。

for k, v := range mux.m {
	if !pathMatch(k, path) {
		continue
	}
	if h == nil || len(k) > n {
		n = len(k)
		h = v.h
	}
}
1
2
3
4
5
6
7
8
9

# beego 框架路由实现

目前几乎所有的 Web 应用路由实现都是基于 http 默认的路由器,但是 Go 自带的路由器有几个限制:

  • 不支持参数设定,例如 /user/:uid 这种泛类型匹配
  • 无法很好的支持 REST 模式,无法限制访问的方法,例如上面的例子中,用户访问 /foo,可以用 GET、POST、DELETE、HEAD 等方式访问
  • 一般网站的路由规则太多了,编写繁琐。我前面自己开发了一个 API 应用,路由规则有三十几条,这种路由多了之后其实可以进一步简化,通过 struct 的方法进行一种简化

beego 框架的路由器基于上面的几点限制考虑设计了一种 REST 方式的路由实现,路由设计也是基于上面 Go 默认设计的两点来考虑:存储路由和转发路由

# 存储路由

针对前面所说的限制点,我们首先要解决参数支持就需要用到正则,第二和第三点我们通过一种变通的方法来解决,REST 的方法对应到 struct 的方法中去,然后路由到 struct 而不是函数,这样在转发路由的时候就可以根据 method 来执行不同的方法。

根据上面的思路,我们设计了两个数据类型 controllerInfo (保存路径和对应的 struct,这里是一个 reflect.Type 类型) 和ControllerRegistor (routers 是一个 slice 用来保存用户添加的路由信息,以及 beego 框架的应用信息)

type controllerInfo struct {
	regex          *regexp.Regexp
	params         map[int]string
	controllerType reflect.Type
}

type ControllerRegistor struct {
	routers     []*controllerInfo
	Application *App
}

1
2
3
4
5
6
7
8
9
10
11

ControllerRegistor 对外的接口函数有

func (p *ControllerRegistor) Add(pattern string, c ControllerInterface)
1

详细的实现如下所示:

func (p *ControllerRegistor) Add(pattern string, c ControllerInterface) {
	parts := strings.Split(pattern, "/")

	j := 0
	params := make(map[int]string)
	for i, part := range parts {
		if strings.HasPrefix(part, ":") {
			expr := "([^/]+)"

			// a user may choose to override the defult expression
			// similar to expressjs: ‘/user/:id([0-9]+)’
 
			if index := strings.Index(part, "("); index != -1 {
				expr = part[index:]
				part = part[:index]
			}
			params[j] = part
			parts[i] = expr
			j++
		}
	}

	// recreate the url pattern, with parameters replaced
	// by regular expressions. then compile the regex

	pattern = strings.Join(parts, "/")
	regex, regexErr := regexp.Compile(pattern)
	if regexErr != nil {

		// TODO add error handling here to avoid panic
		panic(regexErr)
		return
	}

	// now create the Route
	t := reflect.Indirect(reflect.ValueOf(c)).Type()
	route := &controllerInfo{}
	route.regex = regex
	route.params = params
	route.controllerType = t

	p.routers = append(p.routers, route)

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

# 静态路由实现

上面我们实现的动态路由的实现,Go 的 http 包默认支持静态文件处理 FileServer,由于我们实现了自定义的路由器,那么静态文件也需要自己设定,beego 的静态文件夹路径保存在全局变量 StaticDir 中,StaticDir是一个 map 类型,实现如下:

func (app *App) SetStaticPath(url string, path string) *App {
	StaticDir[url] = path
	return app
}
1
2
3
4

应用中设置静态路径可以使用如下方式实现:

beego.SetStaticPath("/img","/static/img")
1

# 转发路由

转发路由是基于 ControllerRegistor 里的路由信息来进行转发的,详细的实现如下代码所示:

// AutoRoute
func (p *ControllerRegistor) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	defer func() {
		if err := recover(); err != nil {
			if !RecoverPanic {
				// go back to panic
				panic(err)
			} else {
				Critical("Handler crashed with error", err)
				for i := 1; ; i += 1 {
					_, file, line, ok := runtime.Caller(i)
					if !ok {
						break
					}
					Critical(file, line)
				}
			}
		}
	}()
	var started bool
	for prefix, staticDir := range StaticDir {
		if strings.HasPrefix(r.URL.Path, prefix) {
			file := staticDir + r.URL.Path[len(prefix):]
			http.ServeFile(w, r, file)
			started = true
			return
		}
	}
	requestPath := r.URL.Path

	//find a matching Route
	for _, route := range p.routers {

		// check if Route pattern matches url
		if !route.regex.MatchString(requestPath) {
			continue
		}

		// get submatches (params)
		matches := route.regex.FindStringSubmatch(requestPath)

		// double check that the Route matches the URL pattern.
		if len(matches[0]) != len(requestPath) {
			continue
		}

		params := make(map[string]string)
		if len(route.params) > 0 {
			// add url parameters to the query param map
			values := r.URL.Query()
			for i, match := range matches[1:] {
				values.Add(route.params[i], match)
				params[route.params[i]] = match
			}

			// reassemble query params and add to RawQuery
			r.URL.RawQuery = url.Values(values).Encode() + "&" + r.URL.RawQuery
			// r.URL.RawQuery = url.Values(values).Encode()
		}
		// Invoke the request handler
		vc := reflect.New(route.controllerType)
		init := vc.MethodByName("Init")
		in := make([]reflect.Value, 2)
		ct := &Context{ResponseWriter: w, Request: r, Params: params}
		in[0] = reflect.ValueOf(ct)
		in[1] = reflect.ValueOf(route.controllerType.Name())
		init.Call(in)
		in = make([]reflect.Value, 0)
		method := vc.MethodByName("Prepare")
		method.Call(in)
		if r.Method == "GET" {
			method = vc.MethodByName("Get")
			method.Call(in)
		} else if r.Method == "POST" {
			method = vc.MethodByName("Post")
			method.Call(in)
		} else if r.Method == "HEAD" {
			method = vc.MethodByName("Head")
			method.Call(in)
		} else if r.Method == "DELETE" {
			method = vc.MethodByName("Delete")
			method.Call(in)
		} else if r.Method == "PUT" {
			method = vc.MethodByName("Put")
			method.Call(in)
		} else if r.Method == "PATCH" {
			method = vc.MethodByName("Patch")
			method.Call(in)
		} else if r.Method == "OPTIONS" {
			method = vc.MethodByName("Options")
			method.Call(in)
		}
		if AutoRender {
			method = vc.MethodByName("Render")
			method.Call(in)
		}
		method = vc.MethodByName("Finish")
		method.Call(in)
		started = true
		break
	}

	// if no matches to url, throw a not found exception
	if started == false {
		http.NotFound(w, r)
	}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107

# 使用入门

基于这样的路由设计之后就可以解决前面所说的三个限制点,使用的方式如下所示:

基本的使用注册路由:

beego.BeeApp.RegisterController("/", &controllers.MainController{})
1

参数注册:

beego.BeeApp.RegisterController("/:param", &controllers.UserController{})
1

正则匹配:

beego.BeeApp.RegisterController("/users/:uid([0-9]+)", &controllers.UserController{})
1
  • HTTP 路由
  • 默认的路由实现
  • beego 框架路由实现
  • 存储路由
  • 静态路由实现
  • 转发路由
  • 使用入门