go-zero 之 rest 实战与原理

{"type":"doc","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"go-zero 是一个集成了各种工程实践的 web 和 rpc 框架,其中 rest 是 web 模块,该模块基于 Go 语言原生的 http 包进行构建,是一个轻量的,高性能的,功能完整的,简单易用的 web 框架。使用 rest 能够快速构建 restful 风格 api 服务,同时具备服务监控和弹性服务治理能力","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"快速开始","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"我们先来快速构建一个服务感受一下,使用 rest 创建 http 服务非常简单,官方推荐使用","attrs":{}},{"type":"link","attrs":{"href":"https://github.com/tal-tech/go-zero/tree/master/tools/goctl","title":""},"content":[{"type":"text","text":"goctl","attrs":{}}]},{"type":"text","text":"代码自动生成工具来生成。这里为了演示构建的步骤细节我们手动来创建服务,代码如下:","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"package main\n\nimport (\n \"log\"\n \"net/http\"\n\n \"github.com/tal-tech/go-zero/core/logx\"\n \"github.com/tal-tech/go-zero/core/service\"\n \"github.com/tal-tech/go-zero/rest\"\n \"github.com/tal-tech/go-zero/rest/httpx\"\n)\n\nfunc main() {\n srv, err := rest.NewServer(rest.RestConf{\n Port: 9090, // 侦听端口\n ServiceConf: service.ServiceConf{\n Log: logx.LogConf{Path: \"./logs\"}, // 日志路径\n },\n })\n if err != nil {\n log.Fatal(err)\n }\n defer srv.Stop()\n // 注册路由\n srv.AddRoutes([]rest.Route{ \n {\n Method: http.MethodGet,\n Path: \"/user/info\",\n Handler: userInfo,\n },\n })\n\n srv.Start() // 启动服务\n}\n\ntype User struct {\n Name string `json:\"name\"`\n Addr string `json:\"addr\"`\n Level int `json:\"level\"`\n}\n\nfunc userInfo(w http.ResponseWriter, r *http.Request) {\n var req struct {\n UserId int64 `form:\"user_id\"` // 定义参数\n }\n if err := httpx.Parse(r, &req); err != nil { // 解析参数\n httpx.Error(w, err)\n return\n }\n users := map[int64]*User{\n 1: &User{\"go-zero\", \"shanghai\", 1},\n 2: &User{\"go-queue\", \"beijing\", 2},\n }\n httpx.WriteJson(w, http.StatusOK, users[req.UserId]) // 返回结果\n}\n","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"通过 rest.NewServer 创建服务,示例配置了端口号和日志路径,服务启动后侦听在 9090 端口,并在当前目录下创建 logs 目录同时创建各等级日志文件","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"然后通过 srv.AddRoutes 注册路由,每个路由需要定义该路由的方法、Path 和 Handler,其中 Handler 类型为 http.HandlerFunc","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"最后通过 srv.Start 启动服务,启动服务后通过访问","attrs":{}},{"type":"link","attrs":{"href":"http://localhost:9090/user/info?user_id=1","title":null},"content":[{"type":"text","text":"http://localhost:9090/user/info?user_id=1","attrs":{}}]},{"type":"text","text":"可以看到返回结果","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"{\n name: \"go-zero\",\n addr: \"shanghai\",\n level: 1\n}\n","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"到此一个简单的 http 服务就创建完成了,可见使用 rest 创建 http 服务非常简单,主要分为三个步骤:创建 Server、注册路由、启动服务","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"服务监控","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"服务监控的重要性不言而喻,没有监控我们就没法清晰的了解到服务的运行情况,也就没有办法提前发现问题,当我们感知到问题存在时候往往为时已晚。服务监控甚至和服务本身同等重要,通过监控我们可以了解到当前服务的运行状况,比如当前的资源使用率、接口的 QPS,接口的耗时,错误率等等,以及在业务处理过程中我们也会记录一些日志帮助定位排查问题, 对于微服务的性能问题进行定位的时候我们往往还需要知道整条调用链路。在 rest 中内置了自动的服务的监控,主要分为三个方面:日志、指标和调用链","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"日志","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"快速开始的示例中我们配置了日志的路径,服务启动后会在该路径下生成日志文件,默认情况下所有日志级别均开启,可以通过","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"logx.SetLevel(1)\n","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"来设置日志级别,日志级别的定义如下:","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":null},"content":[{"type":"text","text":"const (\n // InfoLevel logs everything\n InfoLevel = iota\n // ErrorLevel includes errors, slows, stacks\n ErrorLevel\n // SevereLevel only log severe messages\n SevereLevel\n)\n","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"通过 logx 包进行日志记录,比如我们想要在参数解析出错的时候记录一个错误日志如下:","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":null},"content":[{"type":"text","text":"if err := httpx.Parse(r, &req); err != nil { // 解析参数\n logx.Errorf(\"parse req: %v error: %v\", req, err)\n httpx.Error(w, err)\n return\n}\n","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"访问服务的时候我们故意把参数类型传错,因为 user_id 为 int64 类型,我们传入字符串 aaa,参数解析就会出错,查看 error 日志","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":null},"content":[{"type":"text","text":"http://localhost:9090/user/info?user_id=aaa\n","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"{\"@timestamp\":\"2020-12-01T10:37:25.654+08\",\"level\":\"error\",\"content\":\"main.go:47 parse req: {0} error: the value \\\"aaa\\\" cannot parsed as int\"}\n","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"rest 框架中还会记录慢日志,当服务的响应时间大于 3s 的时候就会产生慢日志,慢日志自动记录不需要手动配置,慢日志如下","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"{\"@timestamp\":\"2020-12-01T10:45:47.679+08\",\"level\":\"slow\",\"content\":\"[HTTP] 200 - /user/info?user_id=123 - [::1]:60349 - Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.67 Safari/537.36 - slowcall(5004.3ms)\",\"trace\":\"401274358783b491\",\"span\":\"0\"}\n","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"日志监控对于我们排查问题非常有帮助,但是文件记录的方式并不方便对日志进行检索,在生产环境一般会借助 elk,把日志同步到 elasticsearch 然后通过 kibana 界面实现快速的检索","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"指标","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"服务指标监控的种类繁多,可以根据自身的服务特点进行监控,比较通用的指标有比如:接口 QPS、接口耗时、错误率等等,通过对这些指标的监控可以了解到服务的运行时的一些信息,rest 框架默认支持 prometheus 指标收集能力,通过添加 Prometheus 配置即可查看对应的指标信息","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/60/60265b54cbb1f13e8748730698dd935e.png","alt":"rest_metric","title":"","style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"有了这些指标信息之后就可以配合 grafana 进行界面化的展示","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"link","attrs":{"href":"https://static.gocn.vip/photo/2020/b0392391-7d2d-4acb-97bc-ec76b5c711cc.png?x-oss-process=image/resize,w_900","title":null}}]},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/4b/4b523eaca1f6f2184392b27211b04e68.png","alt":"grafana","title":"","style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"调用链","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在微服务中服务依赖的关系往往比较复杂,那么横跨多个服务的慢请求要如何查询呢?这时候我们需要一个能串联整个调用链路的标识 (traceId) 和表示调用关系的标识 (spanId),也就是使用 traceId 串联起单次请求,用 spanId 记录每一次调用,原理如下图","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/2a/2aba200213032e297d1802c6bf1cb9c3.png","alt":"trace_list","title":"","style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"基于 rest 的 api 服务往往是作为入口,首先会先从 http header 中获取 traceid,如果没有获取到则会生成一个新的 traceid,通过 context 上下文进行传递,我们知道 context 上下文的传递是进程内的,那么跨服务跨进程是如何传递的呢?比如 api 服务调用 rpc 服务其实是利用了 rpc 提供的 metadata 功能,先把上下文中的调用链信息从 context 读取出来存入 metadata,然后再从 metadata 中读取调用链信息再存入 context 中","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/e5/e57ecf7d1f2f98675d77bb6288e51610.png","alt":"context","title":"","style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"rest 默认会把调用链信息记录在日志中,通过在 elk 中搜索某一个 taceid 即可得到所有的调用链信息,日志记录如下","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"{\"@timestamp\":\"2020-12-01T10:03:01.280+08\",\"level\":\"info\",\"content\":\"200 - /user/info?user_id=1 - [::1]:58955 - Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.67 Safari/537.36 - 0.4ms\",\"trace\":\"7a27076abd932c87\",\"span\":\"0\"}\n","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"JWT 鉴权","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"鉴权几乎是每个应用必备的能力,鉴权的方式很多,而 jwt 是其中比较简单和可靠的一种方式,在 rest 框架中内置了 jwt 鉴权功能,jwt 的原理流程如下图","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"link","attrs":{"href":"https://static.gocn.vip/photo/2020/6f21082d-c0d3-449a-b20a-33b71fe44867.png?x-oss-process=image/resize,w_900","title":null}}]},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/41/4163586e85e3e433d944c648d2b1c9ab.png","alt":"jwt","title":"","style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"rest 框架中通过 rest.WithJwt(secret) 启用 jwt 鉴权,其中 secret 为服务器秘钥是不能泄露的,因为需要使用 secret 来算签名验证 payload 是否被篡改,如果 secret 泄露客户端就可以自行签发 token,黑客就能肆意篡改 token 了。我们基于上面的例子进行改造来验证在 rest 中如何使用 jwt 鉴权","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"获取 jwt","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"第一步客户端需要先获取 jwt,在登录接口中实现 jwt 生成逻辑","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"srv.AddRoute(rest.Route{\n Method: http.MethodPost,\n Path: \"/user/login\",\n Handler: userLogin,\n})\n","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"为了演示方便,userLogin 的逻辑非常简单,主要是获取信息然后生成 jwt,获取到的信息存入 jwt payload 中,然后返回 jwt","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"func userLogin(w http.ResponseWriter, r *http.Request) {\n var req struct {\n UserName string `json:\"user_name\"`\n UserId int `json:\"user_id\"`\n }\n if err := httpx.Parse(r, &req); err != nil {\n httpx.Error(w, err)\n return\n }\n token, _ := genToken(accessSecret, map[string]interface{}{\n \"user_id\": req.UserId,\n \"user_name\": req.UserName,\n }, accessExpire)\n\n httpx.WriteJson(w, http.StatusOK, struct {\n UserId int `json:\"user_id\"`\n UserName string `json:\"user_name\"`\n Token string `json:\"token\"`\n }{\n UserId: req.UserId,\n UserName: req.UserName,\n Token: token,\n })\n}\n","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"生成 jwt 的方法如下","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"func genToken(secret string, payload map[string]interface{}, expire int64) (string, error) {\n now := time.Now().Unix()\n claims := make(jwt.MapClaims)\n claims[\"exp\"] = now + expire\n claims[\"iat\"] = now\n for k, v := range payload {\n claims[k] = v\n }\n token := jwt.New(jwt.SigningMethodHS256)\n token.Claims = claims\n return token.SignedString([]byte(secret))\n}\n","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"启动服务后通过 cURL 访问","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"shell"},"content":[{"type":"text","text":"curl -X \"POST\" \"http://localhost:9090/user/login\" \\\n -H 'Content-Type: application/json; charset=utf-8' \\\n -d $'{\n \"user_name\": \"gozero\",\n \"user_id\": 666\n}'\n","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"会得到如下返回结果","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"{\n \"user_id\": 666,\n \"user_name\": \"gozero\",\n \"token\": \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MDYxMDgwNDcsImlhdCI6MTYwNTUwMzI0NywidXNlcl9pZCI6NjY2LCJ1c2VyX25hbWUiOiJnb3plcm8ifQ.hhMd5gc3F9xZwCUoiuFqAWH48xptqnNGph0AKVkTmqM\"\n}\n","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"添加 Header","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"通过 rest.WithJwt(accessSecret) 启用 jwt 鉴权","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"srv.AddRoute(rest.Route{\n Method: http.MethodGet,\n Path: \"/user/data\",\n Handler: userData,\n}, rest.WithJwt(accessSecret))\n","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"访问/user/data 接口返回 401 Unauthorized 鉴权不通过,添加 Authorization Header,即能正常访问","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"shell"},"content":[{"type":"text","text":"curl \"http://localhost:9090/user/data?user_id=1\" \\\n -H 'Authorization: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MDYxMDgwNDcsImlhdCI6MTYwNTUwMzI0NywidXNlcl9pZCI6NjY2LCJ1c2VyX25hbWUiOiJnb3plcm8ifQ.hhMd5gc3F9xZwCUoiuFqAWH48xptqnNGph0AKVkTmqM'\n","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"获取信息","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"一般会将用户的信息比如用户 id 或者用户名存入 jwt 的 payload 中,然后从 jwt 的 payload 中解析出我们预存的信息,即可知道本次请求时哪个用户发起的","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"func userData(w http.ResponseWriter, r *http.Request) {\n var jwt struct {\n UserId int `ctx:\"user_id\"`\n UserName string `ctx:\"user_name\"`\n }\n err := contextx.For(r.Context(), &jwt)\n if err != nil {\n httpx.Error(w, err)\n }\n httpx.WriteJson(w, http.StatusOK, struct {\n UserId int `json:\"user_id\"`\n UserName string `json:\"user_name\"`\n }{\n UserId: jwt.UserId,\n UserName: jwt.UserName,\n })\n}\n","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"实现原理","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"jwt 鉴权的实现在 authhandler.go 中,实现原理也比较简单,先根据 secret 解析 jwt token,验证 token 是否有效,无效或者验证出错则返回 401 Unauthorized","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"func unauthorized(w http.ResponseWriter, r *http.Request, err error, callback UnauthorizedCallback) {\n writer := newGuardedResponseWriter(w)\n\n if err != nil {\n detailAuthLog(r, err.Error())\n } else {\n detailAuthLog(r, noDetailReason)\n }\n if callback != nil {\n callback(writer, r, err)\n }\n\n writer.WriteHeader(http.StatusUnauthorized)\n}\n","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"验证通过后把 payload 中的信息存入 http request 的 context 中","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"ctx := r.Context()\nfor k, v := range claims {\n switch k {\n case jwtAudience, jwtExpire, jwtId, jwtIssueAt, jwtIssuer, jwtNotBefore, jwtSubject:\n // ignore the standard claims\n default:\n ctx = context.WithValue(ctx, k, v)\n }\n}\n\nnext.ServeHTTP(w, r.WithContext(ctx))\n","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"中间件","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"web 框架中的中间件是实现业务和非业务功能解耦的一种方式,在 web 框架中我们可以通过中间件来实现诸如鉴权、限流、熔断等等功能,中间件的原理流程如下图","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"link","attrs":{"href":"https://static.gocn.vip/photo/2020/80d950fa-2712-4d95-b490-14ed72412607.png?x-oss-process=image/resize,w_900","title":null}}]},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/14/14892a8b7d4b2d594b1387430acd1179.png","alt":"handler","title":"","style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"rest 框架中内置了非常丰富的中间件,在 rest/handler 路径下,通过","attrs":{}},{"type":"link","attrs":{"href":"https://github.com/justinas/alice","title":""},"content":[{"type":"text","text":"alice","attrs":{}}]},{"type":"text","text":"工具把所有中间件链接起来,当发起请求时会依次通过每一个中间件,当满足所有条件后最终请求才会到达真正的业务 Handler 执行业务逻辑,上面介绍的 jwt 鉴权就是通过 authHandler 来实现的,框架中内置的都是一些通用的中间件,比如业务上有一些特殊的处理我们也可以自定义中间件","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"func userMiddleware(next http.HandlerFunc) http.HandlerFunc {\n return func(w http.ResponseWriter, r *http.Request) {\n v := r.URL.Query().Get(\"user_id\")\n if v == \"1\" {\n w.WriteHeader(http.StatusForbidden)\n return\n }\n next.ServeHTTP(w, r)\n }\n}\n","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"通过 Use 方法注册中间件","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"srv.Use(userMiddleware)\n","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"当发起请求 user_id 为 1 的时候 http status 就回返回 403 Forbidden","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"路由原理","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"rest 框架中通过 AddRoutes 方法来注册路由,每一个 Route 有 Method、Path 和 Handler 三个属性,Handler 类型为 http.HandlerFunc,添加的路由会被换成 featuredRoutes 定义如下","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"featuredRoutes struct {\n priority bool // 是否优先级\n jwt jwtSetting // jwt配置\n signature signatureSetting // 验签配置\n routes []Route // 通过AddRoutes添加的路由\n }\n","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"featuredRoutes 通过 engine 的 AddRoutes 添加到 engine 的 routes 属性中","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"func (s *engine) AddRoutes(r featuredRoutes) {\n s.routes = append(s.routes, r)\n}\n","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"调用 Start 方法启动服务后会调用 engine 的 Start 方法,然后会调用 StartWithRouter 方法,该方法内通过 bindRoutes 绑定路由","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"func (s *engine) bindRoutes(router httpx.Router) error {\n metrics := s.createMetrics()\n\n for _, fr := range s.routes { \n if err := s.bindFeaturedRoutes(router, fr, metrics); err != nil { // 绑定路由\n return err\n }\n }\n\n return nil\n}\n","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"最终会调用 patRouter 的 Handle 方法进行绑定,patRouter 实现了 Router 接口","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"type Router interface {\n http.Handler\n Handle(method string, path string, handler http.Handler) error\n SetNotFoundHandler(handler http.Handler)\n SetNotAllowedHandler(handler http.Handler)\n}\n","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"patRouter 中每一种请求方法都对应一个树形结构,每个树节点有两个属性 item 为 path 对应的 handler,而 children 为带路径参数和不带路径参数对应的树节点, 定义如下:","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"node struct {\n item interface{}\n children [2]map[string]*node\n}\n\nTree struct {\n root *node\n}\n","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"通过 Tree 的 Add 方法把不同 path 与对应的 handler 注册到该树上我们通过一个图来展示下该树的存储结构,比如我们定义路由如下","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"{\n Method: http.MethodGet,\n Path: \"/user\",\n Handler: userHander,\n},\n{\n Method: http.MethodGet,\n Path: \"/user/infos\",\n Handler: infosHandler,\n},\n{\n Method: http.MethodGet,\n Path: \"/user/info/:id\",\n Handler: infoHandler,\n},","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"路由存储的树形结构如下图","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"link","attrs":{"href":"https://static.gocn.vip/photo/2020/3050b625-7a3b-414e-bf79-5d2a574049d5.png?x-oss-process=image/resize,w_900","title":null}}]},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/6d/6d663e2df56bc709742c8698236e6c85.png","alt":"tree","title":"","style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"当请求来的时候会调用 patRouter 的 ServeHTTP 方法,在该方法中通过 tree.Search 方法找到对应的 handler 进行执行,否则会执行 notFound 或者 notAllow 的逻辑","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"func (pr *patRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n reqPath := path.Clean(r.URL.Path)\n if tree, ok := pr.trees[r.Method]; ok {\n if result, ok := tree.Search(reqPath); ok { // 在树中搜索对应的handler\n if len(result.Params) > 0 {\n r = context.WithPathVars(r, result.Params)\n }\n result.Item.(http.Handler).ServeHTTP(w, r)\n return\n }\n }\n\n allow, ok := pr.methodNotAllowed(r.Method, reqPath)\n if !ok {\n pr.handleNotFound(w, r)\n return\n }\n\n if pr.notAllowed != nil {\n pr.notAllowed.ServeHTTP(w, r)\n } else {\n w.Header().Set(allowHeader, allow)\n w.WriteHeader(http.StatusMethodNotAllowed)\n }\n}","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"总结","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"本文从 rest 框架的基本使用、服务监控、jwt 鉴权、中间件和路由原理等方面进行了介绍,可见 rest 是一个功能强大的 web 框架,还有很多其他的功能由于篇幅有限后续再详细介绍,希望本篇文章能给大家带来帮助","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"项目地址","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"link","attrs":{"href":"https://github.com/tal-tech/go-zero","title":null},"content":[{"type":"text","text":"https://github.com/tal-tech/go-zero","attrs":{}}]}]},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"框架地址","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"link","attrs":{"href":"https://github.com/tal-tech/go-zero/tree/master/rest","title":null},"content":[{"type":"text","text":"https://github.com/tal-tech/go-zero/tree/master/rest","attrs":{}}]}]},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"文档地址","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"link","attrs":{"href":"https://www.yuque.com/tal-tech/go-zero/rhakzy","title":null},"content":[{"type":"text","text":"https://www.yuque.com/tal-tech/go-zero/rhakzy","attrs":{}}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"go-zero在开源3个多月的star曲线如下:","attrs":{}}]},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/ce/ce8edd21d94c0a29da17c61d358d2660.png","alt":null,"title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"欢迎使用并 ","attrs":{}},{"type":"text","marks":[{"type":"strong","attrs":{}}],"text":"star","attrs":{}},{"type":"text","text":" ","attrs":{}},{"type":"link","attrs":{"href":"https://github.com/tal-tech/go-zero","title":""},"content":[{"type":"text","text":"go-zero","attrs":{}}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}}]}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章