Gin 是Golang编写的web框架。它具有类似于martini的API接口,同时比httprouter快40倍的性能。如果你需要较好的性能和友好的开发方式,你会喜欢上Gin。
如果想要安装Gin依赖,你需要安装Go并正确的设置工作空间。
已经安装Go(1.11以上版本,并且启用Go Mod),你可以下面的指令加入依赖: $ go get -u github.com/gin-gonic/gin 在你的代码中引入: import "github/gin-gonic/gin" (可选的)引入net/http。在使用诸如http.StatusOk的时候,他是必须引入的: import "net/http"Gin 使用了定制版的https://github.com/julienschmidt/httprouter
全部性能测试
Benchmark name(1)(2)(3)(4)Benchmark Gin_GithubAll4355027364 ns/op0 B/op0 allocs/opBenchmark Ace_GithubAll4054329670 ns/op0 B/op0 allocs/opBenchmark Aero_GithubAll5763220648 ns/op0 B/opBenchmark Bear_GithubAll9234216179 ns/op86448 B/op943 allocs/opBenchmark Beego_GithubAll7407243496 ns/op71456 B/op609 allocs/opBenchmark Bone_GithubAll4202922835 ns/op720160 B/op8620 allocs/opBenchmark Chi_GithubAll7620238331 ns/op87696 B/op609 allocs/opBenchmark Denco_GithubAll1835564494 ns/op20224 B/op167 allocs/opBenchmark Echo_GithubAll3125138479 ns/op0 B/op0 allocs/opBenchmark GocraftWeb_GithubAll4117300062 ns/op131656 B/op1686 allocs/opBenchmark Goji_GithubAll3274416158 ns/op56112 B/op334 allocs/opBenchmark Gojiv2_GithubAll1402870518 ns/op352720 B/op4321 allocs/opBenchmark GoJsonRest_GithubAll2976401507 ns/op134371 B/op2737 allocs/opBenchmark GoRestful_GithubAll4102913158 ns/op910144 B/op2938 allocs/opBenchmark GorillaMux_GithubAll3463384987 ns/op251650 B/op1994 allocs/opBenchmark GowwwRouter_GithubAll10000143025 ns/op72144 B/op501 allocs/opBenchmark HttpRouter_GithubAll5593821360 ns/op0 B/op0 allocs/opBenchmark HttpTreeMux_GithubAll10000153944 ns/op65856 B/op671 allocs/opBenchmark Kocha_GithubAll10000106315 ns/op23304 B/op843 allocs/opBenchmark LARS_GithubAll4777925084 ns/op0 B/op0 allocs/opBenchmark Macaron_GithubAll3266371907 ns/op149409 B/op1624 allocs/opBenchmark Martini_GithubAll3313444706 ns/op226551 B/op2325 allocs/opBenchmark Pat_GithubAll2734381818 ns/op1483152 B/op26963 allocs/opBenchmark Possum_GithubAll10000164367 ns/op84448 B/op609 allocs/opBenchmark R2router_GithubAll10000160220 ns/op77328 B/op979 allocs/opBenchmark Rivet_GithubAll1462582453 ns/op16272 B/op167 allocs/opBenchmark Tango_GithubAll6255279611 ns/op63826 B/op1618 allocs/opBenchmark TigerTonic_GithubAll2008687874 ns/op193856 B/op4474 allocs/opBenchmark Traffic_GithubAll3553478508 ns/op820744 B/op14114 allocs/opBenchmark Vulcan_GithubAll6885193333 ns/op19894 B/op609 allocs/op (1): 恒定时间的重复操作,数值越高,性能越高。(2): 定量的重复操作,时间越低,性能越高。(3): 占用内存量,数值越低,性能越高。(4): 每次重复操作的平均之间,数值越低,性能越高。json iterator 是一个性能很高的json处理组件
Gin 使用encoding/json作为默认json解析工具,但是你可以通过其他tag改变为jsoniter。
$ go build -tags=jsoniter .你可以在Gin 示例仓库 找到一些可以运行的示例。
请求
POST /post?id=1234&page=1 HTTP/1.1 Content-Type: application/x-www-form-urlencoded name=manu&message=this_is_great目标服务
func main() { router := gin.Default() router.POST("/post", func(c *gin.Context) { id := c.Query("id") page := c.DefaultQuery("page", "0") name := c.PostForm("name") message := c.PostForm("message") fmt.Printf("id: %s; page: %s; name: %s; message: %s", id, page, name, message) }) router.Run(":8080") }响应
id: 1234; page: 1; name: manu; message: this_is_great请求
POST /post?ids[a]=1234&ids[b]=hello HTTP/1.1 Content-Type: application/x-www-form-urlencoded names[first]=thinkerou&names[second]=tianou目标服务
func main() { router := gin.Default() router.POST("/post", func(c *gin.Context) { ids := c.QueryMap("ids") names := c.PostFormMap("names") fmt.Printf("ids: %v; names: %v", ids, names) }) router.Run(":8080") }响应
ids: map[b:hello a:1234]; names: map[second:tianou first:thinkerou]参考问题#774 和详细示例
系统不应该信任(直接使用)文件的文件名。 详情参考:Content-Disposition on MDN 、#1693
文件名始终是可选的,并且不能被应用程序直接使用:路径信息应被删除,并且应完成向服务器文件系统规则的转换。
func main() { router := gin.Default() // 为组合表单(multipart)设置低内存(默认32MiB) router.MaxMultipartMemory = 8 << 20 // 8 MiB router.POST("/upload", func(c *gin.Context) { // 单文件 file, _ := c.FormFile("file") log.Println(file.Filename) // 上传到指定的目的地 c.SaveUploadedFile(file, dst) c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename)) }) router.Run(":8080") }使用curl
curl -X POST http://localhost:8080/upload \ -F "file=@/Users/appleboy/test.zip" \ -H "Content-Type: multipart/form-data"查看更详细的示例代码
func main() { router := gin.Default() // 为组合表单(multipart)设置低内存(默认32MiB) router.MaxMultipartMemory = 8 << 20 // 8 MiB router.POST("/upload", func(c *gin.Context) { // 多表单 form, _ := c.MultipartForm() files := form.File["upload[]"] for _, file := range files { log.Println(file.Filename) // 上传到指定位置 c.SaveUploadedFile(file, dst) } c.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files))) }) router.Run(":8080") }使用curl
curl -X POST http://localhost:8080/upload \ -F "upload[]=@/Users/appleboy/test1.zip" \ -F "upload[]=@/Users/appleboy/test2.zip" \ -H "Content-Type: multipart/form-data"将:
// 默认使用日志和恢复中间件 r := gin.Default()替换为:
r := gin.New()默认情况下,控制台上输出的日志应根据检测到的TTY进行着色。
无颜色的日志
func main() { // 关闭日志颜色 gin.DisableConsoleColor() // 创建默认gin路由器 // 日志和恢复中间件 router := gin.Default() router.GET("/ping", func(c *gin.Context) { c.String(200, "pong") }) router.Run(":8080") }存在颜色的日志
func main() { // 强制使用颜色 gin.ForceConsoleColor() // 创建默认gin路由器 // 日志和恢复中间件 router := gin.Default() router.GET("/ping", func(c *gin.Context) { c.String(200, "pong") }) router.Run(":8080") }如果要将请求体绑定到一种类型,可以使用模型绑定。Gin当前支持绑定json、XML、YAML和标准的表单数据(foo=bar&boo=baz)。
Gin 使用go-playground/validator/v10进行校验。查看使用文档
请注意,您需要在要绑定的所有字段上设置相应的绑定标签(tag)。例如,当需要绑定json类型的数据,进行如下设置json:"filedname"。
Gin提供了两种方式绑定数据
类型:强制绑定(Must bind) 方法:Bind、BindJSON、BindXML、BindQuery、BindYAML、BindHeader行为: 这些方法的底层会调用mustBindWith。如果发生了绑定异常,请求(request)将会直接失败,并返回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 witch 422。 如果你希望控制绑定的更多行为,可以考虑使用ShouldBind。 类型:弱绑定(Should bind) 方法:ShouldBind、ShouldBindJSON、ShouldBindXML、ShouldBindQuery、ShouldBindYAML、ShouldBindHeader行为:这些方法的底层回调用ShouldBindJSON。如果发生了绑定异常,该异常会返回给开发人员,开发者可以适当地处理请求和错误。当使用绑定方法时,Gin会尝试从请求头中的Content-Type值推断绑定依赖。如果你确定需要绑定什么数据,可以使用ShouldBind或者MustBind。
你可以指定那些字段是必须的。如果一个字段声明了:binding:"required",并且在解析的时候,没有该字段,将会返回一个error。
// 从json绑定 type Login struct { User string `form:"user" json:"user" xml:"user" binding:"required"` Password string `form:"password" json:"password" xml:"password" binding:"required"` } func main() { router := gin.Default() // 样例:JOSN绑定 ({"user": "manu", "password": "123"}) router.POST("/loginJSON", func(c *gin.Context) { var json Login if err := c.ShouldBindJSON(&json); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } if json.User != "manu" || json.Password != "123" { c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"}) return } c.JSON(http.StatusOK, gin.H{"status": "you are logged in"}) }) // 样例:XML绑定 ( // <?xml version="1.0" encoding="UTF-8"?> // <root> // <user>user</user> // <password>123</password> // </root>) router.POST("/loginXML", func(c *gin.Context) { var xml Login if err := c.ShouldBindXML(&xml); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } if xml.User != "manu" || xml.Password != "123" { c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"}) return } c.JSON(http.StatusOK, gin.H{"status": "you are logged in"}) }) // 例如:绑定HTML表单(form)(user=manu&password=123) router.POST("/loginForm", func(c *gin.Context) { var form Login // 将会从请求头中content-type推断绑定类型 //This will infer what binder to use depending on the content-type header. if err := c.ShouldBind(&form); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } if form.User != "manu" || form.Password != "123" { c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"}) return } c.JSON(http.StatusOK, gin.H{"status": "you are logged in"}) }) // 监听8080端口 router.Run(":8080") }使用上面的curl命令运行上面的示例时,它返回错误。因为该示例对密码使用binding:"required"。如果对密码使用binding:"-",则在再次运行以上示例时不会返回错误。
注册自定义验证器。详情请查示例代码
package main import ( "net/http" "time" "github.com/gin-gonic/gin" "github.com/gin-gonic/gin/binding" "github.com/go-playground/validator/v10" ) // Booking 包含绑定和验证数据 type Booking struct { CheckIn time.Time `form:"check_in" binding:"required,bookabledate" time_format:"2006-01-02"` CheckOut time.Time `form:"check_out" binding:"required,gtfield=CheckIn" time_format:"2006-01-02"` } var bookableDate validator.Func = func(fl validator.FieldLevel) bool { date, ok := fl.Field().Interface().(time.Time) if ok { today := time.Now() if today.After(date) { return false } } return true } func main() { route := gin.Default() if v, ok := binding.Validator.Engine().(*validator.Validate); ok { v.RegisterValidation("bookabledate", bookableDate) } route.GET("/bookable", getBookable) route.Run(":8085") } func getBookable(c *gin.Context) { var b Booking if err := c.ShouldBindWith(&b, binding.Query); err == nil { c.JSON(http.StatusOK, gin.H{"message": "Booking dates are valid!"}) } else { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) } } $ curl "localhost:8085/bookable?check_in=2030-04-16&check_out=2030-04-17" {"message":"Booking dates are valid!"} $ curl "localhost:8085/bookable?check_in=2030-03-10&check_out=2030-03-09" {"error":"Key: 'Booking.CheckOut' Error:Field validation for 'CheckOut' failed on the 'gtfield' tag"} $ curl "localhost:8085/bookable?check_in=2000-03-09&check_out=2000-03-10" {"error":"Key: 'Booking.CheckIn' Error:Field validation for 'CheckIn' failed on the 'bookabledate' tag"}%结构体等级的校验 可以通过同样的方式进行注册。更多信息请查看结构体校验 。
ShouldBindQuery 方法仅绑定查询参数。详情请看详细信息
package main import ( "log" "github.com/gin-gonic/gin" ) type Person struct { Name string `form:"name"` Address string `form:"address"` } func main() { route := gin.Default() route.Any("/testing", startPage) route.Run(":8085") } func startPage(c *gin.Context) { var person Person if c.ShouldBindQuery(&person) == nil { log.Println("====== Only Bind By Query String ======") log.Println(person.Name) log.Println(person.Address) } c.String(200, "Success") }详细请看详细信息
package main import ( "log" "time" "github.com/gin-gonic/gin" ) type Person struct { Name string `form:"name"` Address string `form:"address"` Birthday time.Time `form:"birthday" time_format:"2006-01-02" time_utc:"1"` CreateTime time.Time `form:"createTime" time_format:"unixNano"` UnixTime time.Time `form:"unixTime" time_format:"unix"` } func main() { route := gin.Default() route.GET("/testing", startPage) route.Run(":8085") } func startPage(c *gin.Context) { var person Person // 如果为Get方法,仅处理Form数据 // 如果为Post方法,首先检查`content-type`,如果是JSON或者XML将会是使用表单数据 if c.ShouldBind(&person) == nil { log.Println(person.Name) log.Println(person.Address) log.Println(person.Birthday) log.Println(person.CreateTime) log.Println(person.UnixTime) } c.String(200, "Success") }使用如下代码进行测试
$ curl -X GET "localhost:8085/testing?name=appleboy&address=xyz&birthday=1992-03-15&createTime=1562400033000000123&unixTime=1562400033"详情请看详细信息
package main import "github.com/gin-gonic/gin" type Person struct { ID string `uri:"id" binding:"required,uuid"` Name string `uri:"name" binding:"required"` } func main() { route := gin.Default() route.GET("/:name/:id", func(c *gin.Context) { var person Person if err := c.ShouldBindUri(&person); err != nil { c.JSON(400, gin.H{"msg": err}) return } c.JSON(200, gin.H{"name": person.Name, "uuid": person.ID}) }) route.Run(":8088") }使用如下代码进行测试
$ curl -v localhost:8088/thinkerou/987fbc97-4bed-5078-9f07-9141ba07c9f3 $ curl -v localhost:8088/thinkerou/not-uuid查看详细信息
main.go
... type myForm struct { Colors []string `form:"colors[]"` } ... func formHandler(c *gin.Context) { var fakeForm myForm c.ShouldBind(&fakeForm) c.JSON(200, gin.H{"color": fakeForm.Colors}) } ...form.html
<form action="/" method="POST"> <p>Check some colors</p> <label for="red">Red</label> <input type="checkbox" name="colors[]" value="red" id="red"> <label for="green">Green</label> <input type="checkbox" name="colors[]" value="green" id="green"> <label for="blue">Blue</label> <input type="checkbox" name="colors[]" value="blue" id="blue"> <input type="submit"> </form>结果:
{"color":["red","green","blue"]}使用下列代码进行测试
$ curl -X POST -v --form name=user --form "avatar=@./avatar.png" http://localhost:8080/profile使用SecureJSON防止json劫持。如果给定的结构是数组值,则默认值在响应主体前加上“ while(1)”。
func main() { r := gin.Default() // 你可以使用你自定义的JSON安全前缀 // r.SecureJsonPrefix(")]}',\n") r.GET("/someJSON", func(c *gin.Context) { names := []string{"lena", "austin", "foo"} // 输出: while(1);["lena","austin","foo"] c.SecureJSON(http.StatusOK, names) }) // 服务运行并监听: 0.0.0.0:8080 r.Run(":8080") }使用JSONP从其他域中的服务器请求数据。如果查询参数回调存在,则将回调添加到响应主体。
func main() { r := gin.Default() r.GET("/JSONP", func(c *gin.Context) { data := gin.H{ "foo": "bar", } // 回调为:x // 输出 : x({\"foo\":\"bar\"}) c.JSONP(http.StatusOK, data) }) // 服务运行并监听: 0.0.0.0:8080 r.Run(":8080") // 客户端 // curl http://127.0.0.1:8080/JSONP?callback=x }通常,JSON用其unicode实体替换特殊的HTML字符,例如<变成\ u003c。如果要按字面意义编码此类字符,则可以改用PureJSON。此功能在Go 1.6及更低版本中不可用。
func main() { r := gin.Default() // 服务unicode实体 r.GET("/json", func(c *gin.Context) { c.JSON(200, gin.H{ "html": "<b>Hello, world!</b>", }) }) // 提供文字字符 r.GET("/purejson", func(c *gin.Context) { c.PureJSON(200, gin.H{ "html": "<b>Hello, world!</b>", }) }) // 服务运行并监听:0.0.0.0:8080 r.Run(":8080") }使用 LoadHTMLGlob() 或 LoadHTMLFiles()
func main() { router := gin.Default() router.LoadHTMLGlob("templates/*") //router.LoadHTMLFiles("templates/template1.html", "templates/template2.html") router.GET("/index", func(c *gin.Context) { c.HTML(http.StatusOK, "index.tmpl", gin.H{ "title": "Main website", }) }) router.Run(":8080") }templates/index.tmpl
<html> <h1> {{ .title }} </h1> </html>使用不同文件夹下的相同名的模版
func main() { router := gin.Default() router.LoadHTMLGlob("templates/**/*") router.GET("/posts/index", func(c *gin.Context) { c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{ "title": "Posts", }) }) router.GET("/users/index", func(c *gin.Context) { c.HTML(http.StatusOK, "users/index.tmpl", gin.H{ "title": "Users", }) }) router.Run(":8080") }templates/posts/index.tmpl
{{ define "posts/index.tmpl" }} <html><h1> {{ .title }} </h1> <p>Using posts/index.tmpl</p> </html> {{ end }}templates/users/index.tmpl
{{ define "users/index.tmpl" }} <html><h1> {{ .title }} </h1> <p>Using users/index.tmpl</p> </html> {{ end }}你可以使用自己的html模版翻译器
import "html/template" func main() { router := gin.Default() html := template.Must(template.ParseFiles("file1", "file2")) router.SetHTMLTemplate(html) router.Run(":8080") }例如使用如下分隔符
r := gin.Default() r.Delims("{[{", "}]}") r.LoadHTMLGlob("/path/to/templates")详情请看[示例代码](See the detail example code.)
main.go
import ( "fmt" "html/template" "net/http" "time" "github.com/gin-gonic/gin" ) func formatAsDate(t time.Time) string { year, month, day := t.Date() return fmt.Sprintf("%d%02d/%02d", year, month, day) } func main() { router := gin.Default() router.Delims("{[{", "}]}") router.SetFuncMap(template.FuncMap{ "formatAsDate": formatAsDate, }) router.LoadHTMLFiles("./testdata/template/raw.tmpl") router.GET("/raw", func(c *gin.Context) { c.HTML(http.StatusOK, "raw.tmpl", gin.H{ "now": time.Date(2017, 07, 01, 0, 0, 0, 0, time.UTC), }) }) router.Run(":8080") }raw.tmpl
Date: {[{.now | formatAsDate}]}结果
Date: 2017/07/01Gin默认仅允许使用html.Template. 检查多模板渲染是否使用诸如go 1.6块模板之类的功能.
发起重定向很简单,内部和外部都可以使用。
r.GET("/test", func(c *gin.Context) { c.Redirect(http.StatusMovedPermanently, "http://www.google.com/") })Post请求重定向。Issue:#444
r.POST("/test", func(c *gin.Context) { c.Redirect(http.StatusFound, "/foo") })发起路由重定向,仿照下方示例使用HandleContext()
r.GET("/test", func(c *gin.Context) { c.Request.URL.Path = "/test2" r.HandleContext(c) }) r.GET("/test2", func(c *gin.Context) { c.JSON(200, gin.H{"hello": "world"}) })在中间件或处理程序中启动新的Goroutines时,不应使用其内部的原始上下文,而必须使用只读副本
func main() { r := gin.Default() r.GET("/long_async", func(c *gin.Context) { // 创建要在goroutine中使用的副本 cCp := c.Copy() go func() { // 用time.Sleep()模拟一个长任务。 5秒 time.Sleep(5 * time.Second) // 请注意,您正在使用复制的上下文“ cCp”,重要 log.Println("Done! in path " + cCp.Request.URL.Path) }() }) r.GET("/long_sync", func(c *gin.Context) { // 用time.Sleep()模拟一个长任务,5秒 time.Sleep(5 * time.Second) // 因为我们没有使用goroutine,所以我们不必复制上下文 log.Println("Done! in path " + c.Request.URL.Path) }) // 服务启动并监听8080端口 r.Run(":8080") }直接使用http.ListenAndServe(),如下
func main() { router := gin.Default() http.ListenAndServe(":8080", router) }或者
func main() { router := gin.Default() s := &http.Server{ Addr: ":8080", Handler: router, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20, } s.ListenAndServe() }1行LetsEncrypt HTTPS服务器的示例。
package main import ( "log" "github.com/gin-gonic/autotls" "github.com/gin-gonic/gin" ) func main() { r := gin.Default() // 监听ping路径 r.GET("/ping", func(c *gin.Context) { c.String(200, "pong") }) log.Fatal(autotls.Run(r, "example1.com", "example2.com")) }自定义自动证书管理器的示例
package main import ( "log" "github.com/gin-gonic/autotls" "github.com/gin-gonic/gin" "golang.org/x/crypto/acme/autocert" ) func main() { r := gin.Default() // 监听ping路径 r.GET("/ping", func(c *gin.Context) { c.String(200, "pong") }) m := autocert.Manager{ Prompt: autocert.AcceptTOS, HostPolicy: autocert.HostWhitelist("example1.com", "example2.com"), Cache: autocert.DirCache("/var/www/.cache"), } log.Fatal(autotls.RunWithManager(r, &m)) }查看相关问题,并尝试以下代码
package main import ( "log" "net/http" "time" "github.com/gin-gonic/gin" "golang.org/x/sync/errgroup" ) var ( g errgroup.Group ) func router01() http.Handler { e := gin.New() e.Use(gin.Recovery()) e.GET("/", func(c *gin.Context) { c.JSON( http.StatusOK, gin.H{ "code": http.StatusOK, "error": "Welcome server 01", }, ) }) return e } func router02() http.Handler { e := gin.New() e.Use(gin.Recovery()) e.GET("/", func(c *gin.Context) { c.JSON( http.StatusOK, gin.H{ "code": http.StatusOK, "error": "Welcome server 02", }, ) }) return e } func main() { server01 := &http.Server{ Addr: ":8080", Handler: router01(), ReadTimeout: 5 * time.Second, WriteTimeout: 10 * time.Second, } server02 := &http.Server{ Addr: ":8081", Handler: router02(), ReadTimeout: 5 * time.Second, WriteTimeout: 10 * time.Second, } g.Go(func() error { err := server01.ListenAndServe() if err != nil && err != http.ErrServerClosed { log.Fatal(err) } return err }) g.Go(func() error { err := server02.ListenAndServe() if err != nil && err != http.ErrServerClosed { log.Fatal(err) } return err }) if err := g.Wait(); err != nil { log.Fatal(err) } }您可以使用几种方法正常执行关机或重新启动。您可以使用为此专门构建的第三方程序包,也可以使用内置程序包中的功能和方法手动执行相同的操作。
我们可以使用fvbock/endless替换掉默认的ListenAndServe。具体信息请查看:问题#296
router := gin.Default() router.GET("/", handler) // [...] endless.ListenAndServe(":4242", router)备选方案
manners: 优雅的关闭Http服务graceful: Graceful是Go软件包,可用于正常关闭http.Handler服务器。grace: 为Go服务器实现平稳重启和零停机部署。如果使用的是Go 1.8或更高版本,则可能不需要使用这些库。考虑使用http.Server的内置Shutdown()方法进行正常关闭。下面的示例描述了它的用法,我们在这里有更多使用gin的示例。
// +build go1.8 package main import ( "context" "log" "net/http" "os" "os/signal" "syscall" "time" "github.com/gin-gonic/gin" ) func main() { router := gin.Default() router.GET("/", func(c *gin.Context) { time.Sleep(5 * time.Second) c.String(http.StatusOK, "Welcome Gin Server") }) srv := &http.Server{ Addr: ":8080", Handler: router, } // Initializing the server in a goroutine so that // it won't block the graceful shutdown handling below go func() { if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed { log.Fatalf("listen: %s\n", err) } }() // Wait for interrupt signal to gracefully shutdown the server with // a timeout of 5 seconds. quit := make(chan os.Signal) // kill (no param) default send syscall.SIGTERM // kill -2 is syscall.SIGINT // kill -9 is syscall.SIGKILL but can't be catch, so don't need add it signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) <-quit log.Println("Shutting down server...") // The context is used to inform the server it has 5 seconds to finish // the request it is currently handling ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() if err := srv.Shutdown(ctx); err != nil { log.Fatal("Server forced to shutdown:", err) } log.Println("Server exiting") }您可以使用 go-assets 将服务器构建为包含模板的单个二进制文件。
func main() { r := gin.New() t, err := loadTemplate() if err != nil { panic(err) } r.SetHTMLTemplate(t) r.GET("/", func(c *gin.Context) { c.HTML(http.StatusOK, "/html/index.tmpl",nil) }) r.Run(":8080") } // loadTemplate加载go-assets-builder嵌入的模板 func loadTemplate() (*template.Template, error) { t := template.New("") for name, file := range Assets.Files { defer file.Close() if file.IsDir() || !strings.HasSuffix(name, ".tmpl") { continue } h, err := ioutil.ReadAll(file) if err != nil { return nil, err } t, err = t.New(name).Parse(string(h)) if err != nil { return nil, err } } return t, nil }请参阅https://github.com/gin-gonic/examples/tree/master/assets-in-binary目录中的完整示例。
以下示例使用自定义结构:
type StructA struct { FieldA string `form:"field_a"` } type StructB struct { NestedStruct StructA FieldB string `form:"field_b"` } type StructC struct { NestedStructPointer *StructA FieldC string `form:"field_c"` } type StructD struct { NestedAnonyStruct struct { FieldX string `form:"field_x"` } FieldD string `form:"field_d"` } func GetDataB(c *gin.Context) { var b StructB c.Bind(&b) c.JSON(200, gin.H{ "a": b.NestedStruct, "b": b.FieldB, }) } func GetDataC(c *gin.Context) { var b StructC c.Bind(&b) c.JSON(200, gin.H{ "a": b.NestedStructPointer, "c": b.FieldC, }) } func GetDataD(c *gin.Context) { var b StructD c.Bind(&b) c.JSON(200, gin.H{ "x": b.NestedAnonyStruct, "d": b.FieldD, }) } func main() { r := gin.Default() r.GET("/getb", GetDataB) r.GET("/getc", GetDataC) r.GET("/getd", GetDataD) r.Run() }Using the command curl command result: 使用指令curl的结果如下:
$ curl "http://localhost:8080/getb?field_a=hello&field_b=world" {"a":{"FieldA":"hello"},"b":"world"} $ curl "http://localhost:8080/getc?field_a=hello&field_c=world" {"a":{"FieldA":"hello"},"c":"world"} $ curl "http://localhost:8080/getd?field_x=hello&field_d=world" {"d":"world","x":{"FieldX":"hello"}}绑定请求正文的常规方法消耗c.Request.Body,不能多次调用它们。
type formA struct { Foo string `json:"foo" xml:"foo" binding:"required"` } type formB struct { Bar string `json:"bar" xml:"bar" binding:"required"` } func SomeHandler(c *gin.Context) { objA := formA{} objB := formB{} // 此c.ShouldBind消耗c.Request.Body,并且无法重用 if errA := c.ShouldBind(&objA); errA == nil { c.String(http.StatusOK, `the body should be formA`) // 由于c.Request.Body现在是EOF,因此总是会发生错误 } else if errB := c.ShouldBind(&objB); errB == nil { c.String(http.StatusOK, `the body should be formB`) } else { ... } }为此,您可以使用c.ShouldBindBodyWith。
func SomeHandler(c *gin.Context) { objA := formA{} objB := formB{} // 这将读取c.Request.Body并将结果存储到上下文中。 if errA := c.ShouldBindBodyWith(&objA, binding.JSON); errA == nil { c.String(http.StatusOK, `the body should be formA`) // 此时,它会重用存储在上下文中的请求体。 } else if errB := c.ShouldBindBodyWith(&objB, binding.JSON); errB == nil { c.String(http.StatusOK, `the body should be formB JSON`) // 它可以接受其他格式 } else if errB2 := c.ShouldBindBodyWith(&objB, binding.XML); errB2 == nil { c.String(http.StatusOK, `the body should be formB XML`) } else { ... } } c.ShouldBindBodyWith在绑定之前将主体存储到上下文中。这对性能有轻微影响,因此,如果足以一次调用绑定,则不应使用此方法。仅某些格式需要此功能JSON,XML,MsgPack,ProtoBuf。对于其他格式,c.ShouldBind()可以多次调用Query,Form,FormPost,FormMultipart,而不会对性能造成任何损害(请参阅#1341)。http.Pusher功能在go.18版本后才开始支持,有关详细信息,请参见golang 博客
package main import ( "html/template" "log" "github.com/gin-gonic/gin" ) var html = template.Must(template.New("https").Parse(` <html> <head> <title>Https Test</title> <script src="/assets/app.js"></script> </head> <body> <h1 style="color:red;">Welcome, Ginner!</h1> </body> </html> `)) func main() { r := gin.Default() r.Static("/assets", "./assets") r.SetHTMLTemplate(html) r.GET("/", func(c *gin.Context) { if pusher := c.Writer.Pusher(); pusher != nil { // use pusher.Push() to do server push if err := pusher.Push("/assets/app.js", nil); err != nil { log.Printf("Failed to push: %v", err) } } c.HTML(200, "https", gin.H{ "status": "success", }) }) // 服务运行并监听8080端口 r.RunTLS(":8080", "./testdata/server.pem", "./testdata/server.key") }默认的日志格式为:
[GIN-debug] POST /foo --> main.main.func1 (3 handlers) [GIN-debug] GET /bar --> main.main.func2 (3 handlers) [GIN-debug] GET /status --> main.main.func3 (3 handlers)你可以使用gin.DebugPrintRouteFunc来声明指定的日志格式信息(例如:json、键值对或其他)进行日志打印。在下面的示例中,我们使用标准日志包记录所有路由,但是您可以使用其他适合您需求的日志工具。
import ( "log" "net/http" "github.com/gin-gonic/gin" ) func main() { r := gin.Default() gin.DebugPrintRouteFunc = func(httpMethod, absolutePath, handlerName string, nuHandlers int) { log.Printf("endpoint %v %v %v %v\n", httpMethod, absolutePath, handlerName, nuHandlers) } r.POST("/foo", func(c *gin.Context) { c.JSON(http.StatusOK, "foo") }) r.GET("/bar", func(c *gin.Context) { c.JSON(http.StatusOK, "bar") }) r.GET("/status", func(c *gin.Context) { c.JSON(http.StatusOK, "ok") }) // 服务运行并监听8080端口 r.Run() }net/http/httptest软件包是HTTP测试的首选方法。
package main func setupRouter() *gin.Engine { r := gin.Default() r.GET("/ping", func(c *gin.Context) { c.String(200, "pong") }) return r } func main() { r := setupRouter() r.Run(":8080") }上方代码的测试用例
package main import ( "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" ) func TestPingRoute(t *testing.T) { router := setupRouter() w := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/ping", nil) router.ServeHTTP(w, req) assert.Equal(t, 200, w.Code) assert.Equal(t, "pong", w.Body.String()) }