Golang GinWeb框架-快速入门/参数解析

开发 前端
Gin是Golang写的Web框架, 功能类似另一个Go框架Martini(暂停维护https://github.com/go-martini/martini), Gin内部使用定制版本的httprouter(一款轻量级高性能HTTP请求路由器,或叫多路复用器), 速度是Martini的40倍, Gin拥有强大的性能,高效率,以及可扩展性, 所以赶快用起来吧!

[[353617]]

Gin是Golang写的Web框架, 功能类似另一个Go框架Martini(暂停维护https://github.com/go-martini/martini), Gin内部使用定制版本的httprouter(一款轻量级高性能HTTP请求路由器,或叫多路复用器), 速度是Martini的40倍, Gin拥有强大的性能,高效率,以及可扩展性, 所以赶快用起来吧!

安装

Go版本要求: Go1.12及以上

1. 执行以下命令安装最新版本Gin

  1. $ go get -u github.com/gin-gonic/gin 

2. 在你的代码中导入

  1. import "github.com/gin-gonic/gin" 

3. (可选)导入net/http包, 如果你要使用其中的常量,比如http.StatusOK,则需要导入

  1. import "net/http" 

快速开始

编写main.go,写入以下代码并执行go run main.go, 访问http://localhost:8080/ping, 就可以得到响应消息{"message": "pong"}

  1. package main 
  2.  
  3. import "github.com/gin-gonic/gin" 
  4.  
  5. func main() { 
  6.   r := gin.Default()  //创建默认Gin引擎Engine,内部默认开启了日志和异常恢复中间件 
  7.   r.GET("/ping", func(c *gin.Context) { 
  8.     c.JSON(200, gin.H{ 
  9.       "message""pong"
  10.     }) 
  11.   }) 
  12.   r.Run() //默认在localhost:8080监听 

基准测试


测试结果说明:

Benchmark name: 基准测试项

第(1)列:在固定时间内完成的重复次数, 值越大性能好

第(2)列:执行单次重复任务消耗的纳秒数, 单位ns/op, 值越低越好

第(3)列:执行单次重复任务消耗的堆内存字节数, 单位B/op, 值越低越好

第(4)列:每个重复任务平均分配内存的次数, 单位allocs/op, 值越低越好

Gin V1稳定版特性

  • 零内存分配的路由器
  • 仍然是最快的http路由器和框架
  • 完整的单元测试
  • 严格测试
  • API版本冻结,新发布的版本对你原来的代码兼容

使用jsoniter编译

jsoniter(https://github.com/json-iterator/go)是一个高性能可以替代Golang标准库encoding/json并且完全兼容的包

Gin默认使用encoding/json包,但是你可以使用以下tags修改为jsoniter重新编译源码

  1. go build -tags=jsoniter . 

API示例

你可以访问源码,查看更多接口示例代码:https://github.com/gin-gonic/examples

使用GET,POST,PUT,PATCH,DELETE,OPTIONS

  1. func main() { 
  2.   // Creates a gin router with default middleware: 
  3.   // logger and recovery (crash-free) middleware 
  4.   router := gin.Default() 
  5.  
  6.   router.GET("/someGet", getting) 
  7.   router.POST("/somePost", posting) 
  8.   router.PUT("/somePut", putting) 
  9.   router.DELETE("/someDelete", deleting) 
  10.   router.PATCH("/somePatch", patching) 
  11.   router.HEAD("/someHead", head) 
  12.   router.OPTIONS("/someOptions", options) 
  13.  
  14.   // By default it serves on :8080 unless a 
  15.   // PORT environment variable was defined. 
  16.   router.Run() 
  17.   // router.Run(":3000"for a hard coded port 指定端口 

路径参数

  1. func main() { 
  2.   router := gin.Default() 
  3.  
  4.   // This handler will match /user/john but will not match /useror /user 
  5.   //以下路由只会匹配/user/用户名, 不会匹配/user/或者/user 
  6.   router.GET("/user/:name", func(c *gin.Context) { 
  7.     name := c.Param("name") //使用Param方法从路径中获取参数 
  8.     c.String(http.StatusOK, "Hello %s"name
  9.   }) 
  10.  
  11.   // However, this one will match /user/john/ and also /user/john/send 
  12.   // If no other routers match /user/john, it will redirect to /user/john/ 
  13.   // 以下带冒号:和带星号*组成的路由可以匹配/user/用户名/或/user/用户名/动作,如果/user/用户名没有匹配到其他路由,它会自动重定向到/user/用户名/进行匹配 
  14.   router.GET("/user/:name/*action", func(c *gin.Context) { 
  15.     name := c.Param("name"
  16.     action := c.Param("action"
  17.     message := name + " is " + action 
  18.     c.String(http.StatusOK, message) 
  19.   }) 
  20.  
  21.   // For each matched request Context will hold the route definition 
  22.   // 请求上下文request Context会保存所有匹配上的路由定义到c.FullPath()方法 
  23.   router.POST("/user/:name/*action", func(c *gin.Context) { 
  24.     c.FullPath() == "/user/:name/*action" // true 
  25.   }) 
  26.  
  27.   router.Run(":8080"

查询字符串参数

  1. func main() { 
  2.   router := gin.Default() 
  3.  
  4.   // Query string parameters are parsed using the existing underlying request object. 
  5.   // The request responds to a url matching:  /welcome?firstname=Jane&lastname=Doe 
  6.   // 发送测试请求:/welcome?firstname=Jane&lastname=Doe 
  7.   router.GET("/welcome", func(c *gin.Context) { 
  8.     firstname := c.DefaultQuery("firstname""Guest") //如果没有获取到该键值,则使用第二个参数作为默认值 
  9.     lastname := c.Query("lastname")  
  10.     //上一行的完整写法:c.Request.URL.Query().Get("lastname"
  11.  
  12.     c.String(http.StatusOK, "Hello %s %s", firstname, lastname) 
  13.   }) 
  14.   router.Run(":8080"

URL编码的多种数据类型组成的表单请求

请求内容类型为:application/x-www-form-urlencoded

Content-Type: application/x-www-form-urlencoded

  1. package main 
  2.  
  3. import "github.com/gin-gonic/gin" 
  4.  
  5. func main() { 
  6.   router := gin.Default() 
  7.  
  8.   // 模拟提交表单:curl -XPOST http://localhost:8080/form_post -d "message=消息&nick=昵称" 
  9.   router.POST("/form_post", func(c *gin.Context) { 
  10.     message := c.PostForm("message"
  11.     nick := c.DefaultPostForm("nick""anonymous"
  12.  
  13.     c.JSON(200, gin.H{ 
  14.       "status":  "posted"
  15.       "message": message, 
  16.       "nick":    nick, 
  17.     }) 
  18.   }) 
  19.   router.Run(":8080"
  20. //返回结果: {"message":"消息","nick":"昵称","status":"posted"

查询和提交Post表单相结合

  1. package main 
  2.  
  3. import ( 
  4.   "fmt" 
  5.   "github.com/gin-gonic/gin" 
  6.  
  7. func main() { 
  8.   router := gin.Default() 
  9.  
  10.   router.POST("/post", func(c *gin.Context) { 
  11.  
  12.     id := c.Query("id"
  13.     page := c.DefaultQuery("page""0"
  14.     name := c.PostForm("name"
  15.     message := c.PostForm("message"
  16.  
  17.     fmt.Printf("id: %s; page: %s; name: %s; message: %s\n", id, page, name, message) 
  18.     c.JSON(200, gin.H{ 
  19.       "id": id, 
  20.       "page": page, 
  21.       "name"name
  22.       "message": message, 
  23.     }) 
  24.   }) 
  25.   router.Run(":8080"

模拟发送请求:

  1. curl -XPOST http://localhost:8080/post?id=1234&page=1 -d "name=manu&message=this_is_great" 

返回结果:

  1. {"id":"1234","message":"this_is_great","name":"manu","page":"1"

以Map映射作为查询字符串或Post表单参数

  1. func main() { 
  2.   router := gin.Default() 
  3.  
  4.   router.POST("/post", func(c *gin.Context) { 
  5.  
  6.     ids := c.QueryMap("ids")  //获取查询参数中的Map 
  7.     names := c.PostFormMap("names")   //获取Post表单中的Map 
  8.  
  9.     fmt.Printf("ids: %v; names: %v\n", ids, names) 
  10.   }) 
  11.   router.Run(":8080"

  1. 模拟请求: 
  2. curl -XPOST http://localhost:8080/post?ids[a]=1234&ids[b]=hello -d "names[first]=thinkerou&names[second]=tianou" 
  3. 打印结果: 
  4. ids: map[a:1234 b:hello]; names: map[first:thinkerou second:tianou] 

参考文档

Gin官方仓库:https://github.com/gin-gonic/gin

 

责任编辑:姜华 来源: 云原生云
相关推荐

2020-11-26 10:08:17

Golang GinW

2020-11-25 09:18:15

Golang GinW

2020-12-03 09:28:05

Golang GinW

2020-12-02 11:18:28

Golang GinW

2011-11-08 10:36:42

Java

2020-11-27 07:54:53

Golang GinW

2020-12-10 10:22:48

GinWeb中间件HTTPS

2020-11-25 09:10:39

Golang GinW

2020-12-08 12:05:48

Golang GinW框架HTTPS

2021-07-28 06:51:08

FlaskPythonWeb

2017-09-30 16:06:28

代码注解分析

2020-12-22 08:41:21

GolangPostgreSQL数据库

2023-07-05 08:38:48

GolangGo语言

2024-03-06 09:11:34

2023-10-22 20:20:37

FiberGo

2015-10-29 15:36:19

Redis入门

2009-01-03 14:39:00

ibmdwSpirit

2011-03-08 16:50:35

2009-09-24 15:27:41

Hibernate查询

2010-06-24 13:35:53

GRE协议
点赞
收藏

51CTO技术栈公众号