Golang GinWeb框架7-静态文件/模板渲染

开发 前端
本文接着上文(Golang GinWeb框架6-绑定请求字符串/URI/请求头/复选框/表单类型)继续探索GinWeb框架

[[355468]]

 简介

本文接着上文(Golang GinWeb框架6-绑定请求字符串/URI/请求头/复选框/表单类型)继续探索GinWeb框架

静态文件服务

  1. package main 
  2.  
  3. import ( 
  4.   "github.com/gin-gonic/gin" 
  5.   "log" 
  6.   "net/http" 
  7.   "os" 
  8.  
  9. func main() { 
  10.   router := gin.Default() 
  11.   cwd, _ := os.Getwd()  //获取当前文件目录 
  12.   log.Printf("当前项目路径:%s", cwd) 
  13.   router.Static("/static", cwd) //提供静态文件服务器, 第一个参数为相对路径,第二个参数为根路径, 这个路径一般放置css,js,fonts等静态文件,前端html中采用/static/js/xxx或/static/css/xxx等相对路径的方式引用 
  14.   router.StaticFS("/more_static", http.Dir("./")) //将本地文件树结构映射到前端, 通过浏览器可以访问本地文件系统, 模拟访问:http://localhost:8080/more_static 
  15.   router.StaticFile("/logo.png""./resources/logo.png")  //StaticFile提供单静态单文件服务, 模拟访问:http://localhost:8080/log.png 
  16.  
  17.   // Listen and serve on 0.0.0.0:8080 
  18.   router.Run(":8080"

返回文件数据

  1. package main 
  2.  
  3. import ( 
  4.   "github.com/gin-contrib/cors" 
  5.   "github.com/gin-gonic/gin" 
  6.   "net/http" 
  7.  
  8. func main() { 
  9.   router := gin.Default() 
  10.   router.Use(cors.Default()) 
  11.  
  12.   router.GET("/local/file", func(c *gin.Context) { 
  13.     c.File("./main.go"
  14.   }) 
  15.  
  16.  
  17.   // A FileSystem implements access to a collection of named files. 
  18.   // The elements in a file path are separated by slash ('/', U+002F) 
  19.   // characters, regardless of host operating system convention. 
  20.   // FileSystem接口, 要求实现文件的访问的方法, 提供文件访问服务根路径的HTTP处理器 
  21.   var fs http.FileSystem = http.Dir("./")  //将本地目录作为文件服务根路径 
  22.   router.GET("/fs/file", func(c *gin.Context) { 
  23.     c.FileFromFS("main.go", fs)  //将文件服务系统下的文件数据返回 
  24.   }) 
  25.   router.Run(":8080"
  26. /* 
  27. 模拟访问文件数据: 
  28. curl http://localhost:8080/local/file 
  29.  
  30. 模拟访问文件系统下的文件数据: 
  31. curl http://localhost:8080/fs/file 
  32. */ 

用文件读出器提供文件数据服务

  1. package main 
  2.  
  3. import ( 
  4.   "github.com/gin-gonic/gin" 
  5.   "net/http" 
  6.  
  7. func main() { 
  8.   router := gin.Default() 
  9.   router.GET("/someDataFromReader", func(c *gin.Context) { 
  10.     response, err := http.Get("https://raw.githubusercontent.com/gin-gonic/logo/master/color.png"
  11.     if err != nil || response.StatusCode != http.StatusOK {  //请求链接中的文件出现错误时, 直接返回服务不可用 
  12.       c.Status(http.StatusServiceUnavailable) 
  13.       return 
  14.     } 
  15.  
  16.     reader := response.Body  //用响应体内容构造一个文件读出器 
  17.     defer reader.Close() 
  18.     contentLength := response.ContentLength 
  19.     contentType := response.Header.Get("Content-Type"
  20.  
  21.     extraHeaders := map[string]string{ 
  22.       "Content-Disposition": `attachment; filename="gopher.png"`, 
  23.     } 
  24.     // DataFromReader writes the specified reader into the body stream and updates the HTTP code. 
  25.     // func (c *Context) DataFromReader(code int, contentLength int64, contentType string, reader io.Reader, extraHeaders map[string]string) {} 
  26.     // DataFromReader方法将指定的读出器reader中的内容, 写入http响应体流中, 并更新响应码, 响应头信息等 
  27.     c.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders) 
  28.   }) 
  29.   router.Run(":8080"
  30. /* 
  31. 模拟访问: 
  32. curl http://localhost:8080/someDataFromReader 
  33. */ 

HTML渲染

使用LoadHTMLGlob()方法或LoadHTMLFiles()方法

  1. package main 
  2.  
  3. import ( 
  4.   "github.com/gin-gonic/gin" 
  5.   "net/http" 
  6.  
  7. func main() { 
  8.   router := gin.Default() 
  9.   //LoadHTMLGlob方法以glob模式加载匹配的HTML文件, 并与HTML渲染器结合 
  10.   router.LoadHTMLGlob("templates/*"
  11.   //router.LoadHTMLFiles("templates/template1.html""templates/template2.html"
  12.   router.GET("/index", func(c *gin.Context) { 
  13.     //HTML方法设置响应码, 模板文件名, 渲染替换模板中的值, 设置响应内容类型Content-Type "text/html" 
  14.     c.HTML(http.StatusOK, "index.tmpl", gin.H{ 
  15.       "title""Main website"
  16.     }) 
  17.   }) 
  18.   router.Run(":8080"
  19. /* 
  20. 模拟测试: 
  21. curl http://localhost:8080/index 
  22. */ 

增加模板文件, 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"

posts目录下添加模板文件, 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 }} 

 users目录下添加模板文件, 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 }} 

 自定义模板渲染器

你也可以使用你自定义的HTML模板渲染器, 需要自定义模板文件file1, file2等 

  1. package main 
  2.  
  3. import ( 
  4.   "github.com/gin-gonic/gin" 
  5.   "html/template" 
  6.   "net/http" 
  7.  
  8. func main() { 
  9.   router := gin.Default() 
  10.   //template.ParseFiles(文件1,文件2...)创建一个模板对象, 然后解析一组模板,使用文件名作为模板的名字 
  11.   // Must方法将模板和错误进行包裹, 返回模板的内存地址 一般用于变量初始化,比如:var t = template.Must(template.New("name").Parse("html")) 
  12.   html := template.Must(template.ParseFiles("file1""file2")) 
  13.   router.SetHTMLTemplate(html) //关联模板和HTML渲染器 
  14.  
  15.   router.GET("/index", func(c *gin.Context) { 
  16.     //HTML方法设置响应码, 模板文件名, 渲染替换模板中的值, 设置响应内容类型Content-Type "text/html" 
  17.     c.HTML(http.StatusOK, "file1", gin.H{ 
  18.       "title""Main website"
  19.     }) 
  20.   }) 
  21.   router.Run(":8080"

自定义分隔符

你可以自定义分隔符, 模板中默认的分隔符是{{ }}, 我们也可以修改, 比如下面增加一对中括号

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

自定义模板方法

详见 示例代码.

模板中与后端都定义好模板方法, 模板渲染时执行该方法, 类似过滤器方法, 比如时间格式化操作

  1. package main 
  2.  
  3. import ( 
  4.   "fmt" 
  5.   "html/template" 
  6.   "net/http" 
  7.   "time" 
  8.  
  9.   "github.com/gin-gonic/gin" 
  10.  
  11. func formatAsDate(t time.Time) string { 
  12.   yearmonthday := t.Date()  //Date方法返回年,月,日 
  13.   return fmt.Sprintf("%d%02d/%02d"yearmonthday)  //格式化时间 
  14.  
  15. func main() { 
  16.   router := gin.Default() 
  17.   router.Delims("{[{""}]}") //自定义模板中的左右分隔符 
  18.   //SetFuncMap方法用给定的template.FuncMap设置到Gin引擎上, 后面模板渲染时会调用同名方法 
  19.   //FuncMap是一个map,键名关联方法名, 键值关联方法, 每个方法必须返回一个值, 或者返回两个值,其中第二个是error类型 
  20.   router.SetFuncMap(template.FuncMap{ 
  21.     "formatAsDate": formatAsDate, 
  22.   }) 
  23.   router.LoadHTMLFiles("./testdata/template/raw.tmpl") //加载单个模板文件并与HTML渲染器关联 
  24.  
  25.   router.GET("/raw", func(c *gin.Context) { 
  26.     c.HTML(http.StatusOK, "raw.tmpl", gin.H{ 
  27.       "now"time.Date(2017, 07, 01, 0, 0, 0, 0, time.UTC), 
  28.     }) 
  29.   }) 
  30.  
  31.   router.Run(":8080"
  32.  
  33. /* 
  34. 模拟测试: 
  35. curl http://localhost:8080/raw 
  36. */ 

定义模板文件: raw.tmpl

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

时间格式化结果:

  1. Date: 2017/07/01 

多个模板

Gin默认只使用一个html.Template模板引擎, 也可以参考多模板渲染器使用类似Go1.6的块级模板block template功能.

模板相关详情请参考官方template包

参考文档

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

 

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

2020-12-08 12:05:48

Golang GinW框架HTTPS

2020-12-02 11:18:28

Golang GinW

2020-11-23 10:48:39

Golang GinW

2020-11-26 10:08:17

Golang GinW

2020-12-10 10:22:48

GinWeb中间件HTTPS

2020-11-25 09:18:15

Golang GinW

2020-11-27 07:54:53

Golang GinW

2020-11-25 09:10:39

Golang GinW

2023-10-22 20:20:37

FiberGo

2017-07-25 14:07:14

前端Vue模板渲染

2020-09-04 10:14:02

Linux驱动7内核

2024-04-02 09:55:36

GolangColly开发者

2019-10-14 15:34:10

Web 开发框架

2011-05-18 14:07:59

XSL

2021-05-12 08:54:56

FastAP web 框架数据库操作

2022-01-21 08:21:48

前端vdom渲染

2022-03-30 18:18:33

GolangTiDB数据库

2021-08-09 14:32:34

鸿蒙HarmonyOS应用

2013-07-18 13:30:11

Metro微软

2021-09-30 07:26:15

YamlJsonXml
点赞
收藏

51CTO技术栈公众号