使用gorilla/mux进行HTTP请求路由和验证

开发 前端
gorilla/mux 包以直观的 API 提供了 HTTP 请求路由、验证和其它服务。对于任何类型的 Web 应用程序,gorilla/mux 包在简单直观的 API 中提供请求路由、请求验证和相关服务。 CRUD web 应用程序突出了软件包的主要功能。

https://s3.51cto.com/oss/201812/17/5ee3a75d807cf20418bf3271fa7fca4c.png

gorilla/mux 包以直观的 API 提供了 HTTP 请求路由、验证和其它服务。

Go 网络库包括 http.ServeMux 结构类型,它支持 HTTP 请求多路复用(路由):Web 服务器将托管资源的 HTTP 请求与诸如 /sales4today 之类的 URI 路由到代码处理程序;处理程序在发送 HTTP 响应(通常是 HTML 页面)之前执行适当的逻辑。 这是该体系的草图:

  1.              +-----------+     +--------+     +---------+
  2. HTTP 请求---->| web 服务器 |---->| 路由 |---->| 处理程序 |
  3.              +-----------+     +--------+     +---------+

调用 ListenAndServe 方法后启动 HTTP 服务器:

  1. http.ListenAndServe(":8888", nil) // args: port & router

第二个参数 nil 意味着 DefaultServeMux 用于请求路由。

gorilla/mux 库包含 mux.Router 类型,可替代 DefaultServeMux 或自定义请求多路复用器。 在 ListenAndServe 调用中,mux.Router 实例将代替 nil 作为第二个参数。 下面的示例代码很好的说明了为什么 mux.Router如此吸引人:

1、一个简单的 CRUD web 应用程序

crud web 应用程序(见下文)支持四种 CRUD(创建/读取/更新/删除)操作,它们分别对应四种 HTTP 请求方法:POST、GET、PUT 和 DELETE。 在这个 CRUD 应用程序中,所管理的资源是套话与反套话的列表,每个都是套话及其反面的的套话,例如这对:

  1. Out of sight, out of mind. Absence makes the heart grow fonder.

可以添加新的套话对,可以编辑或删除现有的套话对。

CRUD web 应用程序:

  1. package main
  2.  
  3. import (
  4. "gorilla/mux"
  5. "net/http"
  6. "fmt"
  7. "strconv"
  8. )
  9.  
  10. const GETALL string = "GETALL"
  11. const GETONE string = "GETONE"
  12. const POST string = "POST"
  13. const PUT string = "PUT"
  14. const DELETE string = "DELETE"
  15.  
  16. type clichePair struct {
  17. Id int
  18. Cliche string
  19. Counter string
  20. }
  21.  
  22. // Message sent to goroutine that accesses the requested resource.
  23. type crudRequest struct {
  24. verb string
  25. cp *clichePair
  26. id int
  27. cliche string
  28. counter string
  29. confirm chan string
  30. }
  31.  
  32. var clichesList = []*clichePair{}
  33. var masterId = 1
  34. var crudRequests chan *crudRequest
  35.  
  36. // GET /
  37. // GET /cliches
  38. func ClichesAll(res http.ResponseWriter, req *http.Request) {
  39. cr := &crudRequest{verb: GETALL, confirm: make(chan string)}
  40. completeRequest(cr, res, "read all")
  41. }
  42.  
  43. // GET /cliches/id
  44. func ClichesOne(res http.ResponseWriter, req *http.Request) {
  45. id := getIdFromRequest(req)
  46. cr := &crudRequest{verb: GETONE, id: id, confirm: make(chan string)}
  47. completeRequest(cr, res, "read one")
  48. }
  49.  
  50. // POST /cliches
  51. func ClichesCreate(res http.ResponseWriter, req *http.Request) {
  52. cliche, counter := getDataFromRequest(req)
  53. cp := new(clichePair)
  54. cp.Cliche = cliche
  55. cp.Counter = counter
  56. cr := &crudRequest{verb: POST, cp: cp, confirm: make(chan string)}
  57. completeRequest(cr, res, "create")
  58. }
  59.  
  60. // PUT /cliches/id
  61. func ClichesEdit(res http.ResponseWriter, req *http.Request) {
  62. id := getIdFromRequest(req)
  63. cliche, counter := getDataFromRequest(req)
  64. cr := &crudRequest{verb: PUT, id: id, cliche: cliche, counter: counter, confirm: make(chan string)}
  65. completeRequest(cr, res, "edit")
  66. }
  67.  
  68. // DELETE /cliches/id
  69. func ClichesDelete(res http.ResponseWriter, req *http.Request) {
  70. id := getIdFromRequest(req)
  71. cr := &crudRequest{verb: DELETE, id: id, confirm: make(chan string)}
  72. completeRequest(cr, res, "delete")
  73. }
  74.  
  75. func completeRequest(cr *crudRequest, res http.ResponseWriter, logMsg string) {
  76. crudRequests<-cr
  77. msg := <-cr.confirm
  78. res.Write([]byte(msg))
  79. logIt(logMsg)
  80. }
  81.  
  82. func main() {
  83. populateClichesList()
  84.  
  85. // From now on, this gorountine alone accesses the clichesList.
  86. crudRequests = make(chan *crudRequest, 8)
  87. go func() { // resource manager
  88. for {
  89. select {
  90. case req := <-crudRequests:
  91. if req.verb == GETALL {
  92. req.confirm<-readAll()
  93. } else if req.verb == GETONE {
  94. req.confirm<-readOne(req.id)
  95. } else if req.verb == POST {
  96. req.confirm<-addPair(req.cp)
  97. } else if req.verb == PUT {
  98. req.confirm<-editPair(req.id, req.cliche, req.counter)
  99. } else if req.verb == DELETE {
  100. req.confirm<-deletePair(req.id)
  101. }
  102. }
  103. }()
  104. startServer()
  105. }
  106.  
  107. func startServer() {
  108. router := mux.NewRouter()
  109.  
  110. // Dispatch map for CRUD operations.
  111. router.HandleFunc("/", ClichesAll).Methods("GET")
  112. router.HandleFunc("/cliches", ClichesAll).Methods("GET")
  113. router.HandleFunc("/cliches/{id:[0-9]+}", ClichesOne).Methods("GET")
  114.  
  115. router.HandleFunc("/cliches", ClichesCreate).Methods("POST")
  116. router.HandleFunc("/cliches/{id:[0-9]+}", ClichesEdit).Methods("PUT")
  117. router.HandleFunc("/cliches/{id:[0-9]+}", ClichesDelete).Methods("DELETE")
  118.  
  119. http.Handle("/", router) // enable the router
  120.  
  121. // Start the server.
  122. port := ":8888"
  123. fmt.Println("\nListening on port " + port)
  124. http.ListenAndServe(port, router); // mux.Router now in play
  125. }
  126.  
  127. // Return entire list to requester.
  128. func readAll() string {
  129. msg := "\n"
  130. for _, cliche := range clichesList {
  131. next := strconv.Itoa(cliche.Id) + ": " + cliche.Cliche + " " + cliche.Counter + "\n"
  132. msg += next
  133. }
  134. return msg
  135. }
  136.  
  137. // Return specified clichePair to requester.
  138. func readOne(id int) string {
  139. msg := "\n" + "Bad Id: " + strconv.Itoa(id) + "\n"
  140.  
  141. index := findCliche(id)
  142. if index >= 0 {
  143. cliche := clichesList[index]
  144. msg = "\n" + strconv.Itoa(id) + ": " + cliche.Cliche + " " + cliche.Counter + "\n"
  145. }
  146. return msg
  147. }
  148.  
  149. // Create a new clichePair and add to list
  150. func addPair(cp *clichePair) string {
  151. cp.Id = masterId
  152. masterId++
  153. clichesList = append(clichesList, cp)
  154. return "\nCreated: " + cp.Cliche + " " + cp.Counter + "\n"
  155. }
  156.  
  157. // Edit an existing clichePair
  158. func editPair(id int, cliche string, counter string) string {
  159. msg := "\n" + "Bad Id: " + strconv.Itoa(id) + "\n"
  160. index := findCliche(id)
  161. if index >= 0 {
  162. clichesList[index].Cliche = cliche
  163. clichesList[index].Counter = counter
  164. msg = "\nCliche edited: " + cliche + " " + counter + "\n"
  165. }
  166. return msg
  167. }
  168.  
  169. // Delete a clichePair
  170. func deletePair(id int) string {
  171. idStr := strconv.Itoa(id)
  172. msg := "\n" + "Bad Id: " + idStr + "\n"
  173. index := findCliche(id)
  174. if index >= 0 {
  175. clichesList = append(clichesList[:index], clichesList[index + 1:]...)
  176. msg = "\nCliche " + idStr + " deleted\n"
  177. }
  178. return msg
  179. }
  180.  
  181. //*** utility functions
  182. func findCliche(id int) int {
  183. for i := 0; i < len(clichesList); i++ {
  184. if id == clichesList[i].Id {
  185. return i;
  186. }
  187. }
  188. return -1 // not found
  189. }
  190.  
  191. func getIdFromRequest(req *http.Request) int {
  192. vars := mux.Vars(req)
  193. id, _ := strconv.Atoi(vars["id"])
  194. return id
  195. }
  196.  
  197. func getDataFromRequest(req *http.Request) (string, string) {
  198. // Extract the user-provided data for the new clichePair
  199. req.ParseForm()
  200. form := req.Form
  201. cliche := form["cliche"][0] // 1st and only member of a list
  202. counter := form["counter"][0] // ditto
  203. return cliche, counter
  204. }
  205.  
  206. func logIt(msg string) {
  207. fmt.Println(msg)
  208. }
  209.  
  210. func populateClichesList() {
  211. var cliches = []string {
  212. "Out of sight, out of mind.",
  213. "A penny saved is a penny earned.",
  214. "He who hesitates is lost.",
  215. }
  216. var counterCliches = []string {
  217. "Absence makes the heart grow fonder.",
  218. "Penny-wise and dollar-foolish.",
  219. "Look before you leap.",
  220. }
  221.  
  222. for i := 0; i < len(cliches); i++ {
  223. cp := new(clichePair)
  224. cp.Id = masterId
  225. masterId++
  226. cp.Cliche = cliches[i]
  227. cp.Counter = counterCliches[i]
  228. clichesList = append(clichesList, cp)
  229. }
  230. }

为了专注于请求路由和验证,CRUD 应用程序不使用 HTML 页面作为请求响应。 相反,请求会产生明文响应消息:套话对的列表是对 GET 请求的响应,确认新的套话对已添加到列表中是对 POST 请求的响应,依此类推。 这种简化使得使用命令行实用程序(如 curl)可以轻松地测试应用程序,尤其是 gorilla/mux 组件。

gorilla/mux 包可以从 GitHub 安装。 CRUD app ***期运行;因此,应使用 Control-C 或同等命令终止。 CRUD 应用程序的代码,以及自述文件和简单的 curl 测试,可以在我的网站上找到。

2、请求路由

mux.Router 扩展了 REST 风格的路由,它赋给 HTTP 方法(例如,GET)和 URL 末尾的 URI 或路径(例如 /cliches)相同的权重。 URI 用作 HTTP 动词(方法)的名词。 例如,在HTTP请求中有一个起始行,例如:

  1. GET /cliches

意味着得到所有的套话对,而一个起始线,如:

  1. POST /cliches

意味着从 HTTP 正文中的数据创建一个套话对。

在 CRUD web 应用程序中,有五个函数充当 HTTP 请求的五种变体的请求处理程序:

  1. ClichesAll(...)    # GET: 获取所有的套话对
  2. ClichesOne(...)    # GET: 获取指定的套话对
  3. ClichesCreate(...) # POST: 创建新的套话对
  4. ClichesEdit(...)   # PUT: 编辑现有的套话对
  5. ClichesDelete(...) # DELETE: 删除指定的套话对

每个函数都有两个参数:一个 http.ResponseWriter 用于向请求者发送一个响应,一个指向 http.Request 的指针,该指针封装了底层 HTTP 请求的信息。 使用 gorilla/mux 包可以轻松地将这些请求处理程序注册到Web服务器,并执行基于正则表达式的验证。

CRUD 应用程序中的 startServer 函数注册请求处理程序。 考虑这对注册,router 作为 mux.Router 实例:

  1. router.HandleFunc("/", ClichesAll).Methods("GET")
  2. router.HandleFunc("/cliches", ClichesAll).Methods("GET")

这些语句意味着对单斜线 //cliches 的 GET 请求应该路由到 ClichesAll 函数,然后处理请求。 例如,curl 请求(使用 作为命令行提示符):

  1. % curl --request GET localhost:8888/

会产生如下结果:

  1. 1: Out of sight, out of mind.  Absence makes the heart grow fonder.
  2. 2: A penny saved is a penny earned.  Penny-wise and dollar-foolish.
  3. 3: He who hesitates is lost.  Look before you leap.

这三个套话对是 CRUD 应用程序中的初始数据。

在这句注册语句中:

  1. router.HandleFunc("/cliches", ClichesAll).Methods("GET")
  2. router.HandleFunc("/cliches", ClichesCreate).Methods("POST")

URI 是相同的(/cliches),但动词不同:***种情况下为 GET 请求,第二种情况下为 POST 请求。 此注册举例说明了 REST 样式的路由,因为仅动词的不同就足以将请求分派给两个不同的处理程序。

注册中允许多个 HTTP 方法,尽管这会影响 REST 风格路由的精髓:

  1. router.HandleFunc("/cliches", DoItAll).Methods("POST", "GET")

除了动词和 URI 之外,还可以在功能上路由 HTTP 请求。 例如,注册

  1. router.HandleFunc("/cliches", ClichesCreate).Schemes("https").Methods("POST")

要求对 POST 请求进行 HTTPS 访问以创建新的套话对。以类似的方式,注册可能需要具有指定的 HTTP 头元素(例如,认证凭证)的请求。

3、 Request validation

gorilla/mux 包采用简单,直观的方法通过正则表达式进行请求验证。 考虑此请求处理程序以获取一个操作:

  1. router.HandleFunc("/cliches/{id:[0-9]+}", ClichesOne).Methods("GET")

此注册排除了 HTTP 请求,例如:

  1. % curl --request GET localhost:8888/cliches/foo

因为 foo 不是十进制数字。该请求导致熟悉的 404(未找到)状态码。 在此处理程序注册中包含正则表达式模式可确保仅在请求 URI 以十进制整数值结束时才调用 ClichesOne 函数来处理请求:

  1. % curl --request GET localhost:8888/cliches/3  # ok

另一个例子,请求如下:

  1. % curl --request PUT --data "..." localhost:8888/cliches

此请求导致状态代码为 405(错误方法),因为 /cliches URI 在 CRUD 应用程序中仅在 GET 和 POST 请求中注册。 像 GET 请求一样,PUT 请求必须在 URI 的末尾包含一个数字 id:

  1. router.HandleFunc("/cliches/{id:[0-9]+}", ClichesEdit).Methods("PUT")

4、并发问题

gorilla/mux 路由器作为单独的 Go 协程执行对已注册的请求处理程序的每次调用,这意味着并发性被内置于包中。 例如,如果有十个同时发出的请求,例如

  1. % curl --request POST --data "..." localhost:8888/cliches

然后 mux.Router 启动十个 Go 协程来执行 ClichesCreate 处理程序。

GET all、GET one、POST、PUT 和 DELETE 中的五个请求操作中,***三个改变了所请求的资源,即包含套话对的共享 clichesList。 因此,CRUD app 需要通过协调对 clichesList 的访问来保证安全的并发性。 在不同但等效的术语中,CRUD app 必须防止 clichesList 上的竞争条件。 在生产环境中,可以使用数据库系统来存储诸如 clichesList 之类的资源,然后可以通过数据库事务来管理安全并发。

CRUD 应用程序采用推荐的Go方法来实现安全并发:

  • 只有一个 Go 协程,资源管理器在 CRUD app startServer 函数中启动,一旦 Web 服务器开始侦听请求,就可以访问 clichesList
  • 诸如 ClichesCreateClichesAll 之类的请求处理程序向 Go 通道发送(指向)crudRequest 实例(默认情况下是线程安全的),并且资源管理器单独从该通道读取。 然后,资源管理器对 clichesList 执行请求的操作。

安全并发体系结构绘制如下:

  1.            crudRequest                读/写
  2.  
  3. 请求处理程序 -------------> 资源托管者 ------------> 套话列表

在这种架构中,不需要显式锁定 clichesList,因为一旦 CRUD 请求开始进入,只有一个 Go 协程(资源管理器)访问 clichesList

为了使 CRUD 应用程序尽可能保持并发,在一方请求处理程序与另一方的单一资源管理器之间进行有效的分工至关重要。 在这里,为了审查,是 ClichesCreate 请求处理程序:

  1. func ClichesCreate(res http.ResponseWriter, req *http.Request) {
  2. cliche, counter := getDataFromRequest(req)
  3. cp := new(clichePair)
  4. cp.Cliche = cliche
  5. cp.Counter = counter
  6. cr := &crudRequest{verb: POST, cp: cp, confirm: make(chan string)}
  7. completeRequest(cr, res, "create")
  8. }

ClichesCreate 调用实用函数 getDataFromRequest,它从 POST 请求中提取新的套话和反套话。 然后 ClichesCreate 函数创建一个新的 ClichePair,设置两个字段,并创建一个 crudRequest 发送给单个资源管理器。 此请求包括一个确认通道,资源管理器使用该通道将信息返回给请求处理程序。 所有设置工作都可以在不涉及资源管理器的情况下完成,因为尚未访问 clichesList

请求处理程序调用实用程序函数,该函数从 POST 请求中提取新的套话和反套话。 然后,该函数创建一个新的,设置两个字段,并创建一个 crudRequest 发送到单个资源管理器。 此请求包括一个确认通道,资源管理器使用该通道将信息返回给请求处理程序。 所有设置工作都可以在不涉及资源管理器的情况下完成,因为尚未访问它。

completeRequest 实用程序函数在 ClichesCreate 函数和其他请求处理程序的末尾调用:

  1. completeRequest(cr, res, "create") // shown above

通过将 crudRequest 放入 crudRequests 频道,使资源管理器发挥作用:

  1. func completeRequest(cr *crudRequest, res http.ResponseWriter, logMsg string) {
  2.    crudRequests<-cr          // 向资源托管者发送请求
  3.    msg := <-cr.confirm       // 等待确认
  4.    res.Write([]byte(msg))    // 向请求方发送确认
  5.    logIt(logMsg)             // 打印到标准输出
  6. }

对于 POST 请求,资源管理器调用实用程序函数 addPair,它会更改 clichesList 资源:

  1. func addPair(cp *clichePair) string {
  2.    cp.Id = masterId  // 分配一个唯一的 ID
  3.    masterId++        // 更新 ID 计数器
  4.    clichesList = append(clichesList, cp) // 更新列表
  5.    return "\nCreated: " + cp.Cliche + " " + cp.Counter + "\n"
  6. }

资源管理器为其他 CRUD 操作调用类似的实用程序函数。 值得重复的是,一旦 Web 服务器开始接受请求,资源管理器就是唯一可以读取或写入 clichesList 的 goroutine。

对于任何类型的 Web 应用程序,gorilla/mux 包在简单直观的 API 中提供请求路由、请求验证和相关服务。 CRUD web 应用程序突出了软件包的主要功能。 

责任编辑:庞桂玉 来源: Linux中国
相关推荐

2023-10-30 10:17:02

Go编程语言

2022-07-18 11:06:36

Go 语言GORM 库数据库

2021-08-30 14:23:05

BlazorHTTP请求

2013-01-18 10:31:20

JMeterHTTP负载

2010-02-26 09:18:24

Visual Stud

2010-11-30 15:31:38

SharePoint Kerberos

2010-06-11 17:12:28

EIGRP路由协议

2018-07-24 13:01:52

前端优化前端性能浏览器

2023-06-28 11:36:41

2017-08-31 15:20:03

PythonPython3HTTP

2020-12-03 07:43:03

JS Ajax JavaScript

2021-12-27 10:46:07

WebAPIserver签名

2017-10-26 13:40:26

微信小程序Fly

2020-11-26 10:08:17

Golang GinW

2018-10-18 10:05:43

HTTP网络协议TCP

2020-08-23 09:04:04

SSH身份验证FIDO2 USB

2009-04-03 13:20:05

C#扩展方法调用

2022-06-06 06:10:00

密码验证安全

2009-09-22 12:57:42

ibmdwWeb

2019-03-01 09:55:28

HTTPMock架构
点赞
收藏

51CTO技术栈公众号