Golang GinWeb框架9-编译模板/自定义结构体绑定/http2/操作Cookie

开发 前端
本文接着上文(Golang GinWeb框架8-重定向/自定义中间件/认证/HTTPS支持/优雅重启等)继续探索GinWeb框架.

 [[356839]]

简介

本文接着上文(Golang GinWeb框架8-重定向/自定义中间件/认证/HTTPS支持/优雅重启等)继续探索GinWeb框架.

将模板文件一起编译为一个二进制单文件

使用go-assets, 你可以将模板文件和服务一起编译为一个二进制的单文件, 可以方便快捷的部署该服务. 请参考go资产编译器go-assets-builder

使用方法:

  1. 1.下载依赖包 
  2. go get github.com/gin-gonic/gin 
  3. go get github.com/jessevdk/go-assets-builder 
  4.  
  5. 2.将html文件夹(包含html代码)生成为go资产文件assets.go 
  6. go-assets-builder html -o assets.go 
  7.  
  8. 3.编译构建,将服务打包为单二进制文件 
  9. go build -o assets-in-binary 
  10.  
  11. 4.运行服务 
  12. ./assets-in-binary 

go资产文件go-assets.go参考内容如下:

  1. package main 
  2.  
  3. import ( 
  4.   "time" 
  5.  
  6.   "github.com/jessevdk/go-assets" 
  7.  
  8. var _Assetsbfa8d115ce0617d89507412d5393a462f8e9b003 = "<!doctype html>\n<body>\n  <p>Can you see this? → {{.Bar}}</p>\n</body>\n" 
  9. var _Assets3737a75b5254ed1f6d588b40a3449721f9ea86c2 = "<!doctype html>\n<body>\n  <p>Hello, {{.Foo}}</p>\n</body>\n" 
  10.  
  11. // Assets returns go-assets FileSystem 
  12. var Assets = assets.NewFileSystem(map[string][]string{"/": {"html"}, "/html": {"bar.tmpl""index.tmpl"}}, map[string]*assets.File{ 
  13.   "/": { 
  14.     Path:     "/"
  15.     FileMode: 0x800001ed, 
  16.     Mtime:    time.Unix(1524365738, 1524365738517125470), 
  17.     Data:     nil, 
  18.   }, "/html": { 
  19.     Path:     "/html"
  20.     FileMode: 0x800001ed, 
  21.     Mtime:    time.Unix(1524365491, 1524365491289799093), 
  22.     Data:     nil, 
  23.   }, "/html/bar.tmpl": { 
  24.     Path:     "/html/bar.tmpl"
  25.     FileMode: 0x1a4, 
  26.     Mtime:    time.Unix(1524365491, 1524365491289611557), 
  27.     Data:     []byte(_Assetsbfa8d115ce0617d89507412d5393a462f8e9b003), 
  28.   }, "/html/index.tmpl": { 
  29.     Path:     "/html/index.tmpl"
  30.     FileMode: 0x1a4, 
  31.     Mtime:    time.Unix(1524365491, 1524365491289995821), 
  32.     Data:     []byte(_Assets3737a75b5254ed1f6d588b40a3449721f9ea86c2), 
  33.   }}, ""

 main.go

  1. package main 
  2.  
  3. import ( 
  4.   "github.com/gin-gonic/gin" 
  5.   "io/ioutil" 
  6.   "net/http" 
  7.   "strings" 
  8.   "html/template" 
  9.  
  10.  
  11. func main() { 
  12.   r := gin.New() 
  13.  
  14.   t, err := loadTemplate() //加载go-assets-builder生成的模板 
  15.   if err != nil { 
  16.     panic(err) 
  17.   } 
  18.   r.SetHTMLTemplate(t) 
  19.  
  20.   r.GET("/", func(c *gin.Context) { 
  21.     c.HTML(http.StatusOK, "/html/index.tmpl",nil) 
  22.   }) 
  23.   r.Run(":8080"
  24.  
  25. // loadTemplate loads templates embedded by go-assets-builder 
  26. // 加载go-assets-builder生成的资产文件, 返回模板的地址 
  27. func loadTemplate() (*template.Template, error) { 
  28.   t := template.New(""
  29.   for name, file := range Assets.Files { 
  30.     defer file.Close() 
  31.     if file.IsDir() || !strings.HasSuffix(name".tmpl") {  //跳过目录或没有.tmpl后缀的文件 
  32.       continue 
  33.     } 
  34.     h, err := ioutil.ReadAll(file) 
  35.     if err != nil { 
  36.       return nil, err 
  37.     } 
  38.     t, err = t.New(name).Parse(string(h))  //新建一个模板, 文件名做为模板名, 文件内容作为模板内容 
  39.     if err != nil { 
  40.       return nil, err 
  41.     } 
  42.   } 
  43.   return t, nil 

完整示例请查看该目录

使用自定义的结构绑定请求表单

参考实例代码:

  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.  
  48.     r.Run() 

使用命令 curl 模拟请求测试和结果如下:

  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"}} 

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

常规的方法绑定请求体是调用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.   // 使用c.ShoudBind消费c.Request.Body, 但是它只能调用一次 
  12.   if errA := c.ShouldBind(&objA); errA == nil { 
  13.     c.String(http.StatusOK, `the body should be formA`) 
  14.   // Always an error is occurred by this because c.Request.Body is EOF now. 
  15.   //这里会报错,因为c.Request.Body已经被消费, 会返回文件结束符EOF 
  16.   } else if errB := c.ShouldBind(&objB); errB == nil { 
  17.     c.String(http.StatusOK, `the body should be formB`) 
  18.   } else { 
  19.     ... 
  20.   } 

为了解决这个问题, 可以使用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.   // c.ShouldBindBodyWith方法读取c.Request.Body,并且将结果存储到上下文 
  6.   if errA := c.ShouldBindBodyWith(&objA, binding.JSON); errA == nil { 
  7.     c.String(http.StatusOK, `the body should be formA`) 
  8.   // At this time, it reuses body stored in the context. 
  9.   //再次调用c.ShouldBindBodyWith时, 可以从上下文中复用请求体内容 
  10.   } else if errB := c.ShouldBindBodyWith(&objB, binding.JSON); errB == nil { 
  11.     c.String(http.StatusOK, `the body should be formB JSON`) 
  12.   // And it can accepts other formats 也可以接受其他类型的绑定,比如XML 
  13.   } else if errB2 := c.ShouldBindBodyWith(&objB, binding.XML); errB2 == nil { 
  14.     c.String(http.StatusOK, `the body should be formB XML`) 
  15.   } else { 
  16.     ... 
  17.   } 
  • c.ShouldBindBodyWith 该方法在绑定前, 将请求体存储到gin上下文中, 所以这会对性能有轻微的影响, 所以如果你只打算绑定一次的时候, 不应该使用该方法.
  • 这种方式仅仅支持以下格式: JSON, XML, MsgPack,ProtoBuf. 对于其他格式, Query, Form, FormPost, FormMultipart, 可以重复使用c.ShouldBind()方法, 而不会带来类似的性能影响, 详见(#1341)

http2服务推送

为了解决HTTP/1.X的网络资源利用率不够高, 延迟问题等, HTTP/2 引入了服务器推送机制来解决这些问题.

http.Pusher需要go1.8+版本支持. 详见golang博客.

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

 定义路由日志格式

默认路由日志如下:

  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方法自定义日志格式, 下面的示例, 我们用日志log标准库记录路由器日志, 当然你也可以使用其他适合业务的日志工具.

  1. package main 
  2.  
  3. import ( 
  4.   "log" 
  5.   "net/http" 
  6.  
  7.   "github.com/gin-gonic/gin" 
  8.  
  9. func main() { 
  10.   r := gin.Default() 
  11.   //使用DebugPrintRouteFunc设置路由日志记录格式, 这里使用标准库log包记录请求方法/请求路径/控制器名/控制器链个数, 
  12.   gin.DebugPrintRouteFunc = func(httpMethod, absolutePath, handlerName string, nuHandlers int) { 
  13.     log.Printf("endpoint %v %v %v %v\n", httpMethod, absolutePath, handlerName, nuHandlers) 
  14.   } 
  15.  
  16.   r.POST("/foo", func(c *gin.Context) { 
  17.     c.JSON(http.StatusOK, "foo"
  18.   }) 
  19.  
  20.   r.GET("/bar", func(c *gin.Context) { 
  21.     c.JSON(http.StatusOK, "bar"
  22.   }) 
  23.  
  24.   r.GET("/status", func(c *gin.Context) { 
  25.     c.JSON(http.StatusOK, "ok"
  26.   }) 
  27.  
  28.   // Listen and Server in http://0.0.0.0:8080 
  29.   r.Run() 

设置和读取Cookie

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

测试

推荐使用net/http/httptest 包做HTTP测试.

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

测试代码示例:

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

Gin框架用户

其他优质的项目也使用GinWeb框架.

  • gorush: 一个用GO实现的推送通知系统
  • fnproject: 原生容器化, 无服务的跨云平台
  • photoprism: 使用Go和Google的TensorFlow框架支持的个人照片管理
  • krakend: 带有中间件的极致高性能API网关
  • picfit: 使用Go实现的一款图片编辑服务器
  • brigade: 为Kubernetes服务的基于事件驱动的脚本
  • dkron: 分布式, 可靠的任务调度系统

参考文档

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

 

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

2020-11-25 09:18:15

Golang GinW

2020-12-03 09:28:05

Golang GinW

2020-11-26 10:08:17

Golang GinW

2020-11-25 09:10:39

Golang GinW

2020-12-08 12:05:48

Golang GinW框架HTTPS

2020-11-23 10:48:39

Golang GinW

2010-03-01 11:10:41

WCF绑定元素

2023-09-06 10:33:40

夜莺监控数据库

2021-05-28 08:58:41

Golang网卡metrics

2015-08-13 10:31:18

Java 9新功能

2023-10-31 09:10:39

2020-12-02 11:18:28

Golang GinW

2020-11-27 07:54:53

Golang GinW

2011-03-02 10:24:23

DashboardAndroid用户界面设计模板

2009-06-25 14:53:35

自定义UI组件JSF框架

2017-09-22 10:53:52

HTTPHTTP2TCP协议

2023-07-28 09:26:43

GolangZap

2011-12-05 15:02:21

Knockout

2021-01-14 19:04:36

框架数据库mybatis

2009-07-07 14:32:47

JDK日志Formatter
点赞
收藏

51CTO技术栈公众号