当前位置:   article > 正文

Gin框架 快速入门_gin 标签

gin 标签

Gin 是一个 go 写的 web 框架,具有高性能的优点。官方地址:https://github.com/gin-gonic/gin

另一篇很不错的gin入门文章,参考:https://www.jianshu.com/p/4053e77b68d5?utm_campaign=haruki

安装

要安装Gin包,首先需要安装Go并设置Go工作区

1、下载并安装

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

2、在代码中导入它

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

使用包管理工具Govendor安装

1、go get govendor(安装)

$ go get github.com/kardianos/govendor

2、创建项目文件夹并进入文件夹

GOPATH/src/github.com/myusername/project && cd "$_"

3、初始化项目并添加 gin

$ govendor init

$ govendor fetch github.com/gin-gonic/gin@v1.3

4、复制一个模板到你的项目

$ curl https://raw.githubusercontent.com/gin-gonic/gin/master/examples/basic/main.go > main.go

5、运行项目

$ go run main.go

前提

使用gin需要Go的版本号为1.6或更高

快速入门

运行这段代码并在浏览器中访问 http://localhost:8080

  1. package main
  2. import "github.com/gin-gonic/gin"
  3. func main() {
  4. r := gin.Default()
  5. r.GET("/ping", func(c *gin.Context) {
  6. c.JSON(200, gin.H{
  7. "message": "pong",
  8. })
  9. })
  10. r.Run() // listen and serve on 0.0.0.0:8080
  11. }

代码示例

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

  1. func main() {
  2. // Disable Console Color
  3. // gin.DisableConsoleColor()
  4. // 使用默认中间件创建一个gin路由器
  5. // logger and recovery (crash-free) 中间件
  6. router := gin.Default()
  7. router.GET("/someGet", getting)
  8. router.POST("/somePost", posting)
  9. router.PUT("/somePut", putting)
  10. router.DELETE("/someDelete", deleting)
  11. router.PATCH("/somePatch", patching)
  12. router.HEAD("/someHead", head)
  13. router.OPTIONS("/someOptions", options)
  14. // 默认启动的是 8080端口,也可以自己定义启动端口
  15. router.Run()
  16. // router.Run(":3000") for a hard coded port
  17. }

获取路径中的参数

  1. func main() {
  2. router := gin.Default()
  3. // 此规则能够匹配/user/john这种格式,但不能匹配/user//user这种格式
  4. router.GET("/user/:name", func(c *gin.Context) {
  5. name := c.Param("name")
  6. c.String(http.StatusOK, "Hello %s", name)
  7. })
  8. // 但是,这个规则既能匹配/user/john/格式也能匹配/user/john/send这种格式
  9. // 如果没有其他路由器匹配/user/john,它将重定向到/user/john/
  10. router.GET("/user/:name/*action", func(c *gin.Context) {
  11. name := c.Param("name")
  12. action := c.Param("action")
  13. message := name + " is " + action
  14. c.String(http.StatusOK, message)
  15. })
  16. router.Run(":8080")
  17. }

获取Get参数

  1. func main() {
  2. router := gin.Default()
  3. // 匹配的url格式: /welcome?firstname=Jane&lastname=Doe
  4. router.GET("/welcome", func(c *gin.Context) {
  5. firstname := c.DefaultQuery("firstname", "Guest")
  6. lastname := c.Query("lastname") // 是 c.Request.URL.Query().Get("lastname") 的简写
  7. c.String(http.StatusOK, "Hello %s %s", firstname, lastname)
  8. })
  9. router.Run(":8080")
  10. }

获取Post参数

  1. func main() {
  2. router := gin.Default()
  3. router.POST("/form_post", func(c *gin.Context) {
  4. message := c.PostForm("message")
  5. nick := c.DefaultPostForm("nick", "anonymous") // 此方法可以设置默认值
  6. c.JSON(200, gin.H{
  7. "status": "posted",
  8. "message": message,
  9. "nick": nick,
  10. })
  11. })
  12. router.Run(":8080")
  13. }

Get + Post 混合

  1. 示例:
  2. POST /post?id=1234&page=1 HTTP/1.1
  3. Content-Type: application/x-www-form-urlencoded
  4. name=manu&message=this_is_great
  1. func main() {
  2. router := gin.Default()
  3. router.POST("/post", func(c *gin.Context) {
  4. id := c.Query("id")
  5. page := c.DefaultQuery("page", "0")
  6. name := c.PostForm("name")
  7. message := c.PostForm("message")
  8. fmt.Printf("id: %s; page: %s; name: %s; message: %s", id, page, name, message)
  9. })
  10. router.Run(":8080")
  11. }
结果:id: 1234; page: 1; name: manu; message: this_is_great

上传文件

单文件上传

参考问题 #774,细节 example code

慎用 file.Filename ,参考 Content-Disposition on MDN#1693

上传文件的文件名可以由用户自定义,所以可能包含非法字符串,为了安全起见,应该由服务端统一文件名规则

  1. func main() {
  2. router := gin.Default()
  3. // 给表单限制上传大小 (默认 32 MiB)
  4. // router.MaxMultipartMemory = 8 << 20 // 8 MiB
  5. router.POST("/upload", func(c *gin.Context) {
  6. // 单文件
  7. file, _ := c.FormFile("file")
  8. log.Println(file.Filename)
  9. // 上传文件到指定的路径
  10. // c.SaveUploadedFile(file, dst)
  11. c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))
  12. })
  13. router.Run(":8080")
  14. }

curl 测试:

  1. curl -X POST http://localhost:8080/upload \
  2. -F "file=@/Users/appleboy/test.zip" \
  3. -H "Content-Type: multipart/form-data"

多文件上传

详细示例:example code

  1. func main() {
  2. router := gin.Default()
  3. // 给表单限制上传大小 (默认 32 MiB)
  4. // router.MaxMultipartMemory = 8 << 20 // 8 MiB
  5. router.POST("/upload", func(c *gin.Context) {
  6. // 多文件
  7. form, _ := c.MultipartForm()
  8. files := form.File["upload[]"]
  9. for _, file := range files {
  10. log.Println(file.Filename)
  11. // 上传文件到指定的路径
  12. // c.SaveUploadedFile(file, dst)
  13. }
  14. c.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files)))
  15. })
  16. router.Run(":8080")
  17. }

curl 测试:

  1. curl -X POST http://localhost:8080/upload \
  2. -F "upload[]=@/Users/appleboy/test1.zip" \
  3. -F "upload[]=@/Users/appleboy/test2.zip" \
  4. -H "Content-Type: multipart/form-data"

路由分组

  1. func main() {
  2. router := gin.Default()
  3. // Simple group: v1
  4. v1 := router.Group("/v1")
  5. {
  6. v1.POST("/login", loginEndpoint)
  7. v1.POST("/submit", submitEndpoint)
  8. v1.POST("/read", readEndpoint)
  9. }
  10. // Simple group: v2
  11. v2 := router.Group("/v2")
  12. {
  13. v2.POST("/login", loginEndpoint)
  14. v2.POST("/submit", submitEndpoint)
  15. v2.POST("/read", readEndpoint)
  16. }
  17. router.Run(":8080")
  18. }

无中间件启动

使用

r := gin.New()

代替

  1. // 默认启动方式,包含 Logger、Recovery 中间件
  2. r := gin.Default()

使用中间件

  1. func main() {
  2. // 创建一个不包含中间件的路由器
  3. r := gin.New()
  4. // 全局中间件
  5. // 使用 Logger 中间件
  6. r.Use(gin.Logger())
  7. // 使用 Recovery 中间件
  8. r.Use(gin.Recovery())
  9. // 路由添加中间件,可以添加任意多个
  10. r.GET("/benchmark", MyBenchLogger(), benchEndpoint)
  11. // 路由组中添加中间件
  12. // authorized := r.Group("/", AuthRequired())
  13. // exactly the same as:
  14. authorized := r.Group("/")
  15. // per group middleware! in this case we use the custom created
  16. // AuthRequired() middleware just in the "authorized" group.
  17. authorized.Use(AuthRequired())
  18. {
  19. authorized.POST("/login", loginEndpoint)
  20. authorized.POST("/submit", submitEndpoint)
  21. authorized.POST("/read", readEndpoint)
  22. // nested group
  23. testing := authorized.Group("testing")
  24. testing.GET("/analytics", analyticsEndpoint)
  25. }
  26. // Listen and serve on 0.0.0.0:8080
  27. r.Run(":8080")
  28. }

写日志文件

  1. func main() {
  2. // 禁用控制台颜色
  3. gin.DisableConsoleColor()
  4. // 创建记录日志的文件
  5. f, _ := os.Create("gin.log")
  6. gin.DefaultWriter = io.MultiWriter(f)
  7. // 如果需要将日志同时写入文件和控制台,请使用以下代码
  8. // gin.DefaultWriter = io.MultiWriter(f, os.Stdout)
  9. router := gin.Default()
  10. router.GET("/ping", func(c *gin.Context) {
  11. c.String(200, "pong")
  12. })
  13. router.Run(":8080")
  14. }

自定义日志格式

  1. func main() {
  2. router := gin.New()
  3. // LoggerWithFormatter 中间件会将日志写入 gin.DefaultWriter
  4. // By default gin.DefaultWriter = os.Stdout
  5. router.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {
  6. // 你的自定义格式
  7. return fmt.Sprintf("%s - [%s] \"%s %s %s %d %s \"%s\" %s\"\n",
  8. param.ClientIP,
  9. param.TimeStamp.Format(time.RFC1123),
  10. param.Method,
  11. param.Path,
  12. param.Request.Proto,
  13. param.StatusCode,
  14. param.Latency,
  15. param.Request.UserAgent(),
  16. param.ErrorMessage,
  17. )
  18. }))
  19. router.Use(gin.Recovery())
  20. router.GET("/ping", func(c *gin.Context) {
  21. c.String(200, "pong")
  22. })
  23. router.Run(":8080")
  24. }

输出示例:

::1 - [Fri, 07 Dec 2018 17:04:38 JST] "GET /ping HTTP/1.1 200 122.767µs "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.80 Safari/537.36" "

模型绑定和验证

若要将请求主体绑定到结构体中,请使用模型绑定,目前支持JSON、XML、YAML和标准表单值(foo=bar&boo=baz)的绑定。

Gin使用 go-playground/validator.v8 验证参数,查看完整文档

需要在绑定的字段上设置tag,比如,绑定格式为json,需要这样设置 json:"fieldname"

此外,Gin还提供了两套绑定方法:

  • Must bind
    • Methods - Bind, BindJSON, BindXML, BindQuery, BindYAML
    • Behavior - 这些方法底层使用 MustBindWith,如果存在绑定错误,请求将被以下指令中止 c.AbortWithError(400, err).SetType(ErrorTypeBind),响应状态代码会被设置为400,请求头Content-Type被设置为text/plain; charset=utf-8。注意,如果你试图在此之后设置响应代码,将会发出一个警告 [GIN-debug] [WARNING] Headers were already written. Wanted to override status code 400 with 422,如果你希望更好地控制行为,请使用ShouldBind相关的方法
  • Should bind
    • Methods - ShouldBind, ShouldBindJSON, ShouldBindXML, ShouldBindQuery, ShouldBindYAML
    • Behavior - 这些方法底层使用 ShouldBindWith,如果存在绑定错误,则返回错误,开发人员可以正确处理请求和错误。

当我们使用绑定方法时,Gin会根据Content-Type推断出使用哪种绑定器,如果你确定你绑定的是什么,你可以使用MustBindWith或者BindingWith

你还可以给字段指定特定规则的修饰符,如果一个字段用binding:"required"修饰,并且在绑定时该字段的值为空,那么将返回一个错误。

  1. // 绑定为json
  2. type Login struct {
  3. User string `form:"user" json:"user" xml:"user" binding:"required"`
  4. Password string `form:"password" json:"password" xml:"password" binding:"required"`
  5. }
  6. func main() {
  7. router := gin.Default()
  8. // Example for binding JSON ({"user": "manu", "password": "123"})
  9. router.POST("/loginJSON", func(c *gin.Context) {
  10. var json Login
  11. if err := c.ShouldBindJSON(&json); err != nil {
  12. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  13. return
  14. }
  15. if json.User != "manu" || json.Password != "123" {
  16. c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
  17. return
  18. }
  19. c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
  20. })
  21. // Example for binding XML (
  22. // <?xml version="1.0" encoding="UTF-8"?>
  23. // <root>
  24. // <user>user</user>
  25. // <password>123</password>
  26. // </root>)
  27. router.POST("/loginXML", func(c *gin.Context) {
  28. var xml Login
  29. if err := c.ShouldBindXML(&xml); err != nil {
  30. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  31. return
  32. }
  33. if xml.User != "manu" || xml.Password != "123" {
  34. c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
  35. return
  36. }
  37. c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
  38. })
  39. // Example for binding a HTML form (user=manu&password=123)
  40. router.POST("/loginForm", func(c *gin.Context) {
  41. var form Login
  42. // This will infer what binder to use depending on the content-type header.
  43. if err := c.ShouldBind(&form); err != nil {
  44. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  45. return
  46. }
  47. if form.User != "manu" || form.Password != "123" {
  48. c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
  49. return
  50. }
  51. c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
  52. })
  53. // Listen and serve on 0.0.0.0:8080
  54. router.Run(":8080")
  55. }

请求示例:

  1. $ curl -v -X POST \
  2. http://localhost:8080/loginJSON \
  3. -H 'content-type: application/json' \
  4. -d '{ "user": "manu" }'
  5. > POST /loginJSON HTTP/1.1
  6. > Host: localhost:8080
  7. > User-Agent: curl/7.51.0
  8. > Accept: */*
  9. > content-type: application/json
  10. > Content-Length: 18
  11. >
  12. * upload completely sent off: 18 out of 18 bytes
  13. < HTTP/1.1 400 Bad Request
  14. < Content-Type: application/json; charset=utf-8
  15. < Date: Fri, 04 Aug 2017 03:51:31 GMT
  16. < Content-Length: 100
  17. <
  18. {"error":"Key: 'Login.Password' Error:Field validation for 'Password' failed on the 'required' tag"}

跳过验证:

当使用上面的curl命令运行上面的示例时,返回错误,因为示例中Password字段使用了binding:"required",如果我们使用binding:"-",那么它就不会报错。

自定义验证器

Gin允许我们自定义参数验证器,参考1参考2参考3

  1. package main
  2. import (
  3. "net/http"
  4. "reflect"
  5. "time"
  6. "github.com/gin-gonic/gin"
  7. "github.com/gin-gonic/gin/binding"
  8. "gopkg.in/go-playground/validator.v8"
  9. )
  10. // Booking contains binded and validated data.
  11. type Booking struct {
  12. CheckIn time.Time `form:"check_in" binding:"required,bookabledate" time_format:"2006-01-02"`
  13. CheckOut time.Time `form:"check_out" binding:"required,gtfield=CheckIn" time_format:"2006-01-02"`
  14. }
  15. func bookableDate(
  16. v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value,
  17. field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string,
  18. ) bool {
  19. if date, ok := field.Interface().(time.Time); ok {
  20. today := time.Now()
  21. if today.Year() > date.Year() || today.YearDay() > date.YearDay() {
  22. return false
  23. }
  24. }
  25. return true
  26. }
  27. func main() {
  28. route := gin.Default()
  29. if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
  30. v.RegisterValidation("bookabledate", bookableDate)
  31. }
  32. route.GET("/bookable", getBookable)
  33. route.Run(":8085")
  34. }
  35. func getBookable(c *gin.Context) {
  36. var b Booking
  37. if err := c.ShouldBindWith(&b, binding.Query); err == nil {
  38. c.JSON(http.StatusOK, gin.H{"message": "Booking dates are valid!"})
  39. } else {
  40. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  41. }
  42. }
  1. $ curl "localhost:8085/bookable?check_in=2018-04-16&check_out=2018-04-17"
  2. {"message":"Booking dates are valid!"}
  3. $ curl "localhost:8085/bookable?check_in=2018-03-08&check_out=2018-03-09"
  4. {"error":"Key: 'Booking.CheckIn' Error:Field validation for 'CheckIn' failed on the 'bookabledate' tag"}

只绑定Get参数

ShouldBindQuery 函数只绑定Get参数,不绑定post数据,查看详细信息

  1. package main
  2. import (
  3. "log"
  4. "github.com/gin-gonic/gin"
  5. )
  6. type Person struct {
  7. Name string `form:"name"`
  8. Address string `form:"address"`
  9. }
  10. func main() {
  11. route := gin.Default()
  12. route.Any("/testing", startPage)
  13. route.Run(":8085")
  14. }
  15. func startPage(c *gin.Context) {
  16. var person Person
  17. if c.ShouldBindQuery(&person) == nil {
  18. log.Println("====== Only Bind By Query String ======")
  19. log.Println(person.Name)
  20. log.Println(person.Address)
  21. }
  22. c.String(200, "Success")
  23. }

绑定Get参数或者Post参数

查看详细信息,这个例子很有用,可以自己实践一下

  1. package main
  2. import (
  3. "log"
  4. "time"
  5. "github.com/gin-gonic/gin"
  6. )
  7. type Person struct {
  8. Name string `form:"name"`
  9. Address string `form:"address"`
  10. Birthday time.Time `form:"birthday" time_format:"2006-01-02" time_utc:"1"`
  11. }
  12. func main() {
  13. route := gin.Default()
  14. route.GET("/testing", startPage)
  15. route.Run(":8085")
  16. }
  17. func startPage(c *gin.Context) {
  18. var person Person
  19. // If `GET`, only `Form` binding engine (`query`) used.
  20. // 如果是Get,那么接收不到请求中的Post的数据??
  21. // 如果是Post, 首先判断 `content-type` 的类型 `JSON` or `XML`, 然后使用对应的绑定器获取数据.
  22. // See more at https://github.com/gin-gonic/gin/blob/master/binding/binding.go#L48
  23. if c.ShouldBind(&person) == nil {
  24. log.Println(person.Name)
  25. log.Println(person.Address)
  26. log.Println(person.Birthday)
  27. }
  28. c.String(200, "Success")
  29. }

绑定uri

查看详细信息

  1. package main
  2. import "github.com/gin-gonic/gin"
  3. type Person struct {
  4. ID string `uri:"id" binding:"required,uuid"`
  5. Name string `uri:"name" binding:"required"`
  6. }
  7. func main() {
  8. route := gin.Default()
  9. route.GET("/:name/:id", func(c *gin.Context) {
  10. var person Person
  11. if err := c.ShouldBindUri(&person); err != nil {
  12. c.JSON(400, gin.H{"msg": err})
  13. return
  14. }
  15. c.JSON(200, gin.H{"name": person.Name, "uuid": person.ID})
  16. })
  17. route.Run(":8088")
  18. }

测试用例:

  1. $ curl -v localhost:8088/thinkerou/987fbc97-4bed-5078-9f07-9141ba07c9f3
  2. $ curl -v localhost:8088/thinkerou/not-uuid

绑定HTML复选框

查看详细信息

main.go

  1. ...
  2. type myForm struct {
  3. Colors []string `form:"colors[]"`
  4. }
  5. ...
  6. func formHandler(c *gin.Context) {
  7. var fakeForm myForm
  8. c.ShouldBind(&fakeForm)
  9. c.JSON(200, gin.H{"color": fakeForm.Colors})
  10. }
  11. ...

form.html

  1. <form action="/" method="POST">
  2. <p>Check some colors</p>
  3. <label for="red">Red</label>
  4. <input type="checkbox" name="colors[]" value="red" id="red">
  5. <label for="green">Green</label>
  6. <input type="checkbox" name="colors[]" value="green" id="green">
  7. <label for="blue">Blue</label>
  8. <input type="checkbox" name="colors[]" value="blue" id="blue">
  9. <input type="submit">
  10. </form>

result:

{"color":["red","green","blue"]}

绑定Post参数

  1. package main
  2. import (
  3. "github.com/gin-gonic/gin"
  4. )
  5. type LoginForm struct {
  6. User string `form:"user" binding:"required"`
  7. Password string `form:"password" binding:"required"`
  8. }
  9. func main() {
  10. router := gin.Default()
  11. router.POST("/login", func(c *gin.Context) {
  12. // you can bind multipart form with explicit binding declaration:
  13. // c.ShouldBindWith(&form, binding.Form)
  14. // or you can simply use autobinding with ShouldBind method:
  15. var form LoginForm
  16. // in this case proper binding will be automatically selected
  17. if c.ShouldBind(&form) == nil {
  18. if form.User == "user" && form.Password == "password" {
  19. c.JSON(200, gin.H{"status": "you are logged in"})
  20. } else {
  21. c.JSON(401, gin.H{"status": "unauthorized"})
  22. }
  23. }
  24. })
  25. router.Run(":8080")
  26. }

测试用例:

$ curl -v --form user=user --form password=password http://localhost:8080/login

XML、JSON、YAML和ProtoBuf 渲染(输出格式)

即接口返回的数据格式

  1. func main() {
  2. r := gin.Default()
  3. // gin.H is a shortcut for map[string]interface{}
  4. r.GET("/someJSON", func(c *gin.Context) {
  5. c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
  6. })
  7. r.GET("/moreJSON", func(c *gin.Context) {
  8. // You also can use a struct
  9. var msg struct {
  10. Name string `json:"user"`
  11. Message string
  12. Number int
  13. }
  14. msg.Name = "Lena"
  15. msg.Message = "hey"
  16. msg.Number = 123
  17. // Note that msg.Name becomes "user" in the JSON
  18. // Will output : {"user": "Lena", "Message": "hey", "Number": 123}
  19. c.JSON(http.StatusOK, msg)
  20. })
  21. r.GET("/someXML", func(c *gin.Context) {
  22. c.XML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
  23. })
  24. r.GET("/someYAML", func(c *gin.Context) {
  25. c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
  26. })
  27. r.GET("/someProtoBuf", func(c *gin.Context) {
  28. reps := []int64{int64(1), int64(2)}
  29. label := "test"
  30. // The specific definition of protobuf is written in the testdata/protoexample file.
  31. data := &protoexample.Test{
  32. Label: &label,
  33. Reps: reps,
  34. }
  35. // Note that data becomes binary data in the response
  36. // Will output protoexample.Test protobuf serialized data
  37. c.ProtoBuf(http.StatusOK, data)
  38. })
  39. // Listen and serve on 0.0.0.0:8080
  40. r.Run(":8080")
  41. }

SecureJSON

使用SecureJSON可以防止json劫持,如果返回的数据是数组,则会默认在返回值前加上"while(1)"

  1. func main() {
  2. r := gin.Default()
  3. // 可以自定义返回的json数据前缀
  4. // r.SecureJsonPrefix(")]}',\n")
  5. r.GET("/someJSON", func(c *gin.Context) {
  6. names := []string{"lena", "austin", "foo"}
  7. // 将会输出: while(1);["lena","austin","foo"]
  8. c.SecureJSON(http.StatusOK, names)
  9. })
  10. // Listen and serve on 0.0.0.0:8080
  11. r.Run(":8080")
  12. }

JSONP

使用JSONP可以跨域传输,如果参数中存在回调参数,那么返回的参数将是回调函数的形式

  1. func main() {
  2. r := gin.Default()
  3. r.GET("/JSONP", func(c *gin.Context) {
  4. data := map[string]interface{}{
  5. "foo": "bar",
  6. }
  7. // 访问 http://localhost:8080/JSONP?callback=call
  8. // 将会输出: call({foo:"bar"})
  9. c.JSONP(http.StatusOK, data)
  10. })
  11. // Listen and serve on 0.0.0.0:8080
  12. r.Run(":8080")
  13. }

AsciiJSON

使用AsciiJSON将使特殊字符编码

  1. func main() {
  2. r := gin.Default()
  3. r.GET("/someJSON", func(c *gin.Context) {
  4. data := map[string]interface{}{
  5. "lang": "GO语言",
  6. "tag": "<br>",
  7. }
  8. // 将输出: {"lang":"GO\u8bed\u8a00","tag":"\u003cbr\u003e"}
  9. c.AsciiJSON(http.StatusOK, data)
  10. })
  11. // Listen and serve on 0.0.0.0:8080
  12. r.Run(":8080")
  13. }

PureJSON

通常情况下,JSON会将特殊的HTML字符替换为对应的unicode字符,比如<替换为\u003c,如果想原样输出html,则使用PureJSON,这个特性在Go 1.6及以下版本中无法使用。

  1. func main() {
  2. r := gin.Default()
  3. // Serves unicode entities
  4. r.GET("/json", func(c *gin.Context) {
  5. c.JSON(200, gin.H{
  6. "html": "<b>Hello, world!</b>",
  7. })
  8. })
  9. // Serves literal characters
  10. r.GET("/purejson", func(c *gin.Context) {
  11. c.PureJSON(200, gin.H{
  12. "html": "<b>Hello, world!</b>",
  13. })
  14. })
  15. // listen and serve on 0.0.0.0:8080
  16. r.Run(":8080")
  17. }

设置静态文件路径

访问静态文件需要先设置路径

  1. func main() {
  2. router := gin.Default()
  3. router.Static("/assets", "./assets")
  4. router.StaticFS("/more_static", http.Dir("my_file_system"))
  5. router.StaticFile("/favicon.ico", "./resources/favicon.ico")
  6. // Listen and serve on 0.0.0.0:8080
  7. router.Run(":8080")
  8. }

返回第三方获取的数据

  1. func main() {
  2. router := gin.Default()
  3. router.GET("/someDataFromReader", func(c *gin.Context) {
  4. response, err := http.Get("https://raw.githubusercontent.com/gin-gonic/logo/master/color.png")
  5. if err != nil || response.StatusCode != http.StatusOK {
  6. c.Status(http.StatusServiceUnavailable)
  7. return
  8. }
  9. reader := response.Body
  10. contentLength := response.ContentLength
  11. contentType := response.Header.Get("Content-Type")
  12. extraHeaders := map[string]string{
  13. "Content-Disposition": `attachment; filename="gopher.png"`,
  14. }
  15. c.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders)
  16. })
  17. router.Run(":8080")
  18. }

HTML渲染

使用LoadHTMLGlob() 或者 LoadHTMLFiles()

  1. func main() {
  2. router := gin.Default()
  3. router.LoadHTMLGlob("templates/*")
  4. //router.LoadHTMLFiles("templates/template1.html", "templates/template2.html")
  5. router.GET("/index", func(c *gin.Context) {
  6. c.HTML(http.StatusOK, "index.tmpl", gin.H{
  7. "title": "Main website",
  8. })
  9. })
  10. router.Run(":8080")
  11. }

templates/index.tmpl

  1. <html>
  2. <h1>
  3. {{ .title }}
  4. </h1>
  5. </html>

在不同目录中使用具有相同名称的模板

  1. func main() {
  2. router := gin.Default()
  3. router.LoadHTMLGlob("templates/**/*")
  4. router.GET("/posts/index", func(c *gin.Context) {
  5. c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{
  6. "title": "Posts",
  7. })
  8. })
  9. router.GET("/users/index", func(c *gin.Context) {
  10. c.HTML(http.StatusOK, "users/index.tmpl", gin.H{
  11. "title": "Users",
  12. })
  13. })
  14. router.Run(":8080")
  15. }

templates/posts/index.tmpl

  1. {{ define "posts/index.tmpl" }}
  2. <html><h1>
  3. {{ .title }}
  4. </h1>
  5. <p>Using posts/index.tmpl</p>
  6. </html>
  7. {{ end }}

templates/users/index.tmpl

  1. {{ define "users/index.tmpl" }}
  2. <html><h1>
  3. {{ .title }}
  4. </h1>
  5. <p>Using users/index.tmpl</p>
  6. </html>
  7. {{ end }}

自定义模板渲染器

  1. import "html/template"
  2. func main() {
  3. router := gin.Default()
  4. html := template.Must(template.ParseFiles("file1", "file2"))
  5. router.SetHTMLTemplate(html)
  6. router.Run(":8080")
  7. }

自定义渲染分隔符

  1. r := gin.Default()
  2. r.Delims("{[{", "}]}")
  3. r.LoadHTMLGlob("/path/to/templates")

自定义模板函数

详细信息

main.go

  1. import (
  2. "fmt"
  3. "html/template"
  4. "net/http"
  5. "time"
  6. "github.com/gin-gonic/gin"
  7. )
  8. func formatAsDate(t time.Time) string {
  9. year, month, day := t.Date()
  10. return fmt.Sprintf("%d%02d/%02d", year, month, day)
  11. }
  12. func main() {
  13. router := gin.Default()
  14. router.Delims("{[{", "}]}")
  15. router.SetFuncMap(template.FuncMap{
  16. "formatAsDate": formatAsDate,
  17. })
  18. router.LoadHTMLFiles("./testdata/template/raw.tmpl")
  19. router.GET("/raw", func(c *gin.Context) {
  20. c.HTML(http.StatusOK, "raw.tmpl", map[string]interface{}{
  21. "now": time.Date(2017, 07, 01, 0, 0, 0, 0, time.UTC),
  22. })
  23. })
  24. router.Run(":8080")
  25. }

raw.tmpl

然后就可以在html中直接使用formatAsDate函数了

Date: {[{.now | formatAsDate}]}

Result:

Date: 2017/07/01

多个模板文件

Gin默认情况下只允许使用一个html模板文件(即一次可以加载多个模板文件),点击这里查看实现案例

重定向

发布HTTP重定向很容易,支持内部和外部链接

  1. r.GET("/test", func(c *gin.Context) {
  2. c.Redirect(http.StatusMovedPermanently, "http://www.google.com/")
  3. })

Gin路由重定向,使用如下的HandleContext

  1. r.GET("/test", func(c *gin.Context) {
  2. c.Request.URL.Path = "/test2"
  3. r.HandleContext(c)
  4. })
  5. r.GET("/test2", func(c *gin.Context) {
  6. c.JSON(200, gin.H{"hello": "world"})
  7. })

自定义中间件

  1. func Logger() gin.HandlerFunc {
  2. return func(c *gin.Context) {
  3. t := time.Now()
  4. // Set example variable
  5. c.Set("example", "12345")
  6. // before request
  7. c.Next()
  8. // after request
  9. latency := time.Since(t)
  10. log.Print(latency)
  11. // access the status we are sending
  12. status := c.Writer.Status()
  13. log.Println(status)
  14. }
  15. }
  16. func main() {
  17. r := gin.New()
  18. r.Use(Logger())
  19. r.GET("/test", func(c *gin.Context) {
  20. example := c.MustGet("example").(string)
  21. // it would print: "12345"
  22. log.Println(example)
  23. })
  24. // Listen and serve on 0.0.0.0:8080
  25. r.Run(":8080")
  26. }

使用BasicAuth()(验证)中间件

  1. // simulate some private data
  2. var secrets = gin.H{
  3. "foo": gin.H{"email": "foo@bar.com", "phone": "123433"},
  4. "austin": gin.H{"email": "austin@example.com", "phone": "666"},
  5. "lena": gin.H{"email": "lena@guapa.com", "phone": "523443"},
  6. }
  7. func main() {
  8. r := gin.Default()
  9. // Group using gin.BasicAuth() middleware
  10. // gin.Accounts is a shortcut for map[string]string
  11. authorized := r.Group("/admin", gin.BasicAuth(gin.Accounts{
  12. "foo": "bar",
  13. "austin": "1234",
  14. "lena": "hello2",
  15. "manu": "4321",
  16. }))
  17. // /admin/secrets endpoint
  18. // hit "localhost:8080/admin/secrets
  19. authorized.GET("/secrets", func(c *gin.Context) {
  20. // get user, it was set by the BasicAuth middleware
  21. user := c.MustGet(gin.AuthUserKey).(string)
  22. if secret, ok := secrets[user]; ok {
  23. c.JSON(http.StatusOK, gin.H{"user": user, "secret": secret})
  24. } else {
  25. c.JSON(http.StatusOK, gin.H{"user": user, "secret": "NO SECRET :("})
  26. }
  27. })
  28. // Listen and serve on 0.0.0.0:8080
  29. r.Run(":8080")
  30. }

中间件中使用Goroutines

在中间件或处理程序中启动新的Goroutines时,你不应该使用其中的原始上下文,你必须使用只读副本(c.Copy()

  1. func main() {
  2. r := gin.Default()
  3. r.GET("/long_async", func(c *gin.Context) {
  4. // 创建要在goroutine中使用的副本
  5. cCp := c.Copy()
  6. go func() {
  7. // simulate a long task with time.Sleep(). 5 seconds
  8. time.Sleep(5 * time.Second)
  9. // 这里使用你创建的副本
  10. log.Println("Done! in path " + cCp.Request.URL.Path)
  11. }()
  12. })
  13. r.GET("/long_sync", func(c *gin.Context) {
  14. // simulate a long task with time.Sleep(). 5 seconds
  15. time.Sleep(5 * time.Second)
  16. // 这里没有使用goroutine,所以不用使用副本
  17. log.Println("Done! in path " + c.Request.URL.Path)
  18. })
  19. // Listen and serve on 0.0.0.0:8080
  20. r.Run(":8080")
  21. }

自定义HTTP配置

直接像这样使用http.ListenAndServe()

  1. func main() {
  2. router := gin.Default()
  3. http.ListenAndServe(":8080", router)
  4. }

或者

  1. func main() {
  2. router := gin.Default()
  3. s := &http.Server{
  4. Addr: ":8080",
  5. Handler: router,
  6. ReadTimeout: 10 * time.Second,
  7. WriteTimeout: 10 * time.Second,
  8. MaxHeaderBytes: 1 << 20,
  9. }
  10. s.ListenAndServe()
  11. }

支持Let's Encrypt证书

1行代码实现LetsEncrypt HTTPS服务器

  1. package main
  2. import (
  3. "log"
  4. "github.com/gin-gonic/autotls"
  5. "github.com/gin-gonic/gin"
  6. )
  7. func main() {
  8. r := gin.Default()
  9. // Ping handler
  10. r.GET("/ping", func(c *gin.Context) {
  11. c.String(200, "pong")
  12. })
  13. log.Fatal(autotls.Run(r, "example1.com", "example2.com"))
  14. }

自定义autocert管理器的示例

  1. package main
  2. import (
  3. "log"
  4. "github.com/gin-gonic/autotls"
  5. "github.com/gin-gonic/gin"
  6. "golang.org/x/crypto/acme/autocert"
  7. )
  8. func main() {
  9. r := gin.Default()
  10. // Ping handler
  11. r.GET("/ping", func(c *gin.Context) {
  12. c.String(200, "pong")
  13. })
  14. m := autocert.Manager{
  15. Prompt: autocert.AcceptTOS,
  16. HostPolicy: autocert.HostWhitelist("example1.com", "example2.com"),
  17. Cache: autocert.DirCache("/var/www/.cache"),
  18. }
  19. log.Fatal(autotls.RunWithManager(r, &m))
  20. }

Gin运行多个服务

请参阅问题并尝试以下示例

  1. package main
  2. import (
  3. "log"
  4. "net/http"
  5. "time"
  6. "github.com/gin-gonic/gin"
  7. "golang.org/x/sync/errgroup"
  8. )
  9. var (
  10. g errgroup.Group
  11. )
  12. func router01() http.Handler {
  13. e := gin.New()
  14. e.Use(gin.Recovery())
  15. e.GET("/", func(c *gin.Context) {
  16. c.JSON(
  17. http.StatusOK,
  18. gin.H{
  19. "code": http.StatusOK,
  20. "error": "Welcome server 01",
  21. },
  22. )
  23. })
  24. return e
  25. }
  26. func router02() http.Handler {
  27. e := gin.New()
  28. e.Use(gin.Recovery())
  29. e.GET("/", func(c *gin.Context) {
  30. c.JSON(
  31. http.StatusOK,
  32. gin.H{
  33. "code": http.StatusOK,
  34. "error": "Welcome server 02",
  35. },
  36. )
  37. })
  38. return e
  39. }
  40. func main() {
  41. server01 := &http.Server{
  42. Addr: ":8080",
  43. Handler: router01(),
  44. ReadTimeout: 5 * time.Second,
  45. WriteTimeout: 10 * time.Second,
  46. }
  47. server02 := &http.Server{
  48. Addr: ":8081",
  49. Handler: router02(),
  50. ReadTimeout: 5 * time.Second,
  51. WriteTimeout: 10 * time.Second,
  52. }
  53. g.Go(func() error {
  54. return server01.ListenAndServe()
  55. })
  56. g.Go(func() error {
  57. return server02.ListenAndServe()
  58. })
  59. if err := g.Wait(); err != nil {
  60. log.Fatal(err)
  61. }
  62. }

优雅重启或停止

想要优雅地重启或停止你的Web服务器,使用下面的方法

我们可以使用fvbock/endless来替换默认的ListenAndServe,有关详细信息,请参阅问题#296

  1. router := gin.Default()
  2. router.GET("/", handler)
  3. // [...]
  4. endless.ListenAndServe(":4242", router)

一个替换方案

  • manners:一个Go HTTP服务器,能优雅的关闭
  • graceful:Graceful是一个go的包,支持优雅地关闭http.Handler服务器
  • grace:对Go服务器进行优雅的重启和零停机部署

如果你的Go版本是1.8,你可能不需要使用这个库,考虑使用http.Server内置的Shutdown()方法进行优雅关闭,查看例子

  1. // +build go1.8
  2. package main
  3. import (
  4. "context"
  5. "log"
  6. "net/http"
  7. "os"
  8. "os/signal"
  9. "time"
  10. "github.com/gin-gonic/gin"
  11. )
  12. func main() {
  13. router := gin.Default()
  14. router.GET("/", func(c *gin.Context) {
  15. time.Sleep(5 * time.Second)
  16. c.String(http.StatusOK, "Welcome Gin Server")
  17. })
  18. srv := &http.Server{
  19. Addr: ":8080",
  20. Handler: router,
  21. }
  22. go func() {
  23. // service connections
  24. if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
  25. log.Fatalf("listen: %s\n", err)
  26. }
  27. }()
  28. // Wait for interrupt signal to gracefully shutdown the server with
  29. // a timeout of 5 seconds.
  30. quit := make(chan os.Signal)
  31. signal.Notify(quit, os.Interrupt)
  32. <-quit
  33. log.Println("Shutdown Server ...")
  34. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  35. defer cancel()
  36. if err := srv.Shutdown(ctx); err != nil {
  37. log.Fatal("Server Shutdown:", err)
  38. }
  39. log.Println("Server exiting")
  40. }

构建包含模板的二进制文件

你可以使用go-assets将服务器构建成一个包含模板的二进制文件

  1. func main() {
  2. r := gin.New()
  3. t, err := loadTemplate()
  4. if err != nil {
  5. panic(err)
  6. }
  7. r.SetHTMLTemplate(t)
  8. r.GET("/", func(c *gin.Context) {
  9. c.HTML(http.StatusOK, "/html/index.tmpl",nil)
  10. })
  11. r.Run(":8080")
  12. }
  13. // loadTemplate loads templates embedded by go-assets-builder
  14. func loadTemplate() (*template.Template, error) {
  15. t := template.New("")
  16. for name, file := range Assets.Files {
  17. if file.IsDir() || !strings.HasSuffix(name, ".tmpl") {
  18. continue
  19. }
  20. h, err := ioutil.ReadAll(file)
  21. if err != nil {
  22. return nil, err
  23. }
  24. t, err = t.New(name).Parse(string(h))
  25. if err != nil {
  26. return nil, err
  27. }
  28. }
  29. return t, nil
  30. }

请参见examples/assets-in-binary目录中的例子

使用自定义结构绑定表单数据

以下示例使用自定义结构

  1. type StructA struct {
  2. FieldA string `form:"field_a"`
  3. }
  4. type StructB struct {
  5. NestedStruct StructA
  6. FieldB string `form:"field_b"`
  7. }
  8. type StructC struct {
  9. NestedStructPointer *StructA
  10. FieldC string `form:"field_c"`
  11. }
  12. type StructD struct {
  13. NestedAnonyStruct struct {
  14. FieldX string `form:"field_x"`
  15. }
  16. FieldD string `form:"field_d"`
  17. }
  18. func GetDataB(c *gin.Context) {
  19. var b StructB
  20. c.Bind(&b)
  21. c.JSON(200, gin.H{
  22. "a": b.NestedStruct,
  23. "b": b.FieldB,
  24. })
  25. }
  26. func GetDataC(c *gin.Context) {
  27. var b StructC
  28. c.Bind(&b)
  29. c.JSON(200, gin.H{
  30. "a": b.NestedStructPointer,
  31. "c": b.FieldC,
  32. })
  33. }
  34. func GetDataD(c *gin.Context) {
  35. var b StructD
  36. c.Bind(&b)
  37. c.JSON(200, gin.H{
  38. "x": b.NestedAnonyStruct,
  39. "d": b.FieldD,
  40. })
  41. }
  42. func main() {
  43. r := gin.Default()
  44. r.GET("/getb", GetDataB)
  45. r.GET("/getc", GetDataC)
  46. r.GET("/getd", GetDataD)
  47. r.Run()
  48. }

运行示例:

  1. $ curl "http://localhost:8080/getb?field_a=hello&field_b=world"
  2. {"a":{"FieldA":"hello"},"b":"world"}
  3. $ curl "http://localhost:8080/getc?field_a=hello&field_c=world"
  4. {"a":{"FieldA":"hello"},"c":"world"}
  5. $ curl "http://localhost:8080/getd?field_x=hello&field_d=world"
  6. {"d":"world","x":{"FieldX":"hello"}}

注意:不支持以下样式结构

  1. type StructX struct {
  2. X struct {} `form:"name_x"` // HERE have form
  3. }
  4. type StructY struct {
  5. Y StructX `form:"name_y"` // HERE have form
  6. }
  7. type StructZ struct {
  8. Z *StructZ `form:"name_z"` // HERE have form
  9. }

总之,现在只支持现在没有form标签的自定义结构

将请求体绑定到不同的结构体中

绑定请求体的常规方法使用c.Request.Body,并且不能多次调用

  1. type formA struct {
  2. Foo string `json:"foo" xml:"foo" binding:"required"`
  3. }
  4. type formB struct {
  5. Bar string `json:"bar" xml:"bar" binding:"required"`
  6. }
  7. func SomeHandler(c *gin.Context) {
  8. objA := formA{}
  9. objB := formB{}
  10. // This c.ShouldBind consumes c.Request.Body and it cannot be reused.
  11. if errA := c.ShouldBind(&objA); errA == nil {
  12. c.String(http.StatusOK, `the body should be formA`)
  13. // Always an error is occurred by this because c.Request.Body is EOF now.
  14. } else if errB := c.ShouldBind(&objB); errB == nil {
  15. c.String(http.StatusOK, `the body should be formB`)
  16. } else {
  17. ...
  18. }
  19. }

同样,你能使用c.ShouldBindBodyWith

  1. func SomeHandler(c *gin.Context) {
  2. objA := formA{}
  3. objB := formB{}
  4. // This reads c.Request.Body and stores the result into the context.
  5. if errA := c.ShouldBindBodyWith(&objA, binding.JSON); errA == nil {
  6. c.String(http.StatusOK, `the body should be formA`)
  7. // At this time, it reuses body stored in the context.
  8. } else if errB := c.ShouldBindBodyWith(&objB, binding.JSON); errB == nil {
  9. c.String(http.StatusOK, `the body should be formB JSON`)
  10. // And it can accepts other formats
  11. } else if errB2 := c.ShouldBindBodyWith(&objB, binding.XML); errB2 == nil {
  12. c.String(http.StatusOK, `the body should be formB XML`)
  13. } else {
  14. ...
  15. }
  16. }
  • c.ShouldBindBodyWith 在绑定之前将body存储到上下文中,这对性能有轻微影响,因此如果你要立即调用,则不应使用此方法
  • 此功能仅适用于这些格式 -- JSON, XML, MsgPack, ProtoBuf。对于其他格式,Query, Form, FormPost, FormMultipart, 可以被c.ShouldBind()多次调用而不影响性能(参考 #1341

HTTP/2 服务器推送

http.Pusher只支持Go 1.8或更高版本,有关详细信息,请参阅golang博客

  1. package main
  2. import (
  3. "html/template"
  4. "log"
  5. "github.com/gin-gonic/gin"
  6. )
  7. var html = template.Must(template.New("https").Parse(`
  8. <html>
  9. <head>
  10. <title>Https Test</title>
  11. <script src="/assets/app.js"></script>
  12. </head>
  13. <body>
  14. <h1 style="color:red;">Welcome, Ginner!</h1>
  15. </body>
  16. </html>
  17. `))
  18. func main() {
  19. r := gin.Default()
  20. r.Static("/assets", "./assets")
  21. r.SetHTMLTemplate(html)
  22. r.GET("/", func(c *gin.Context) {
  23. if pusher := c.Writer.Pusher(); pusher != nil {
  24. // use pusher.Push() to do server push
  25. if err := pusher.Push("/assets/app.js", nil); err != nil {
  26. log.Printf("Failed to push: %v", err)
  27. }
  28. }
  29. c.HTML(200, "https", gin.H{
  30. "status": "success",
  31. })
  32. })
  33. // Listen and Server in https://127.0.0.1:8080
  34. r.RunTLS(":8080", "./testdata/server.pem", "./testdata/server.key")
  35. }

自定义路由日志的格式

默认的路由日志是这样的:

  1. [GIN-debug] POST /foo --> main.main.func1 (3 handlers)
  2. [GIN-debug] GET /bar --> main.main.func2 (3 handlers)
  3. [GIN-debug] GET /status --> main.main.func3 (3 handlers)

如果你想以给定的格式记录这些信息(例如 JSON,键值对或其他格式),你可以使用gin.DebugPrintRouteFunc来定义格式,在下面的示例中,我们使用标准日志包记录路由日志,你可以使用其他适合你需求的日志工具

  1. import (
  2. "log"
  3. "net/http"
  4. "github.com/gin-gonic/gin"
  5. )
  6. func main() {
  7. r := gin.Default()
  8. gin.DebugPrintRouteFunc = func(httpMethod, absolutePath, handlerName string, nuHandlers int) {
  9. log.Printf("endpoint %v %v %v %v\n", httpMethod, absolutePath, handlerName, nuHandlers)
  10. }
  11. r.POST("/foo", func(c *gin.Context) {
  12. c.JSON(http.StatusOK, "foo")
  13. })
  14. r.GET("/bar", func(c *gin.Context) {
  15. c.JSON(http.StatusOK, "bar")
  16. })
  17. r.GET("/status", func(c *gin.Context) {
  18. c.JSON(http.StatusOK, "ok")
  19. })
  20. // Listen and Server in http://0.0.0.0:8080
  21. r.Run()
  22. }

设置并获取cookie

  1. import (
  2. "fmt"
  3. "github.com/gin-gonic/gin"
  4. )
  5. func main() {
  6. router := gin.Default()
  7. router.GET("/cookie", func(c *gin.Context) {
  8. cookie, err := c.Cookie("gin_cookie")
  9. if err != nil {
  10. cookie = "NotSet"
  11. c.SetCookie("gin_cookie", "test", 3600, "/", "localhost", false, true)
  12. }
  13. fmt.Printf("Cookie value: %s \n", cookie)
  14. })
  15. router.Run()
  16. }

测试

net/http/httptest包是http测试的首选方式

  1. package main
  2. func setupRouter() *gin.Engine {
  3. r := gin.Default()
  4. r.GET("/ping", func(c *gin.Context) {
  5. c.String(200, "pong")
  6. })
  7. return r
  8. }
  9. func main() {
  10. r := setupRouter()
  11. r.Run(":8080")
  12. }

测试上面的示例代码

  1. package main
  2. import (
  3. "net/http"
  4. "net/http/httptest"
  5. "testing"
  6. "github.com/stretchr/testify/assert"
  7. )
  8. func TestPingRoute(t *testing.T) {
  9. router := setupRouter()
  10. w := httptest.NewRecorder()
  11. req, _ := http.NewRequest("GET", "/ping", nil)
  12. router.ServeHTTP(w, req)
  13. assert.Equal(t, 200, w.Code)
  14. assert.Equal(t, "pong", w.Body.String())
  15. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/336661
推荐阅读
相关标签
  

闽ICP备14008679号