日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關(guān)咨詢(xún)
選擇下列產(chǎn)品馬上在線(xiàn)溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問(wèn)題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷(xiāo)解決方案
GolangGinWeb框架7-靜態(tài)文件/模板渲染

簡(jiǎn)介

本文接著上文(Golang GinWeb框架6-綁定請(qǐng)求字符串/URI/請(qǐng)求頭/復(fù)選框/表單類(lèi)型)繼續(xù)探索GinWeb框架

靜態(tài)文件服務(wù)

 
 
 
 
  1. package main
  2. import (
  3.   "github.com/gin-gonic/gin"
  4.   "log"
  5.   "net/http"
  6.   "os"
  7. )
  8. func main() {
  9.   router := gin.Default()
  10.   cwd, _ := os.Getwd()  //獲取當(dāng)前文件目錄
  11.   log.Printf("當(dāng)前項(xiàng)目路徑:%s", cwd)
  12.   router.Static("/static", cwd) //提供靜態(tài)文件服務(wù)器, 第一個(gè)參數(shù)為相對(duì)路徑,第二個(gè)參數(shù)為根路徑, 這個(gè)路徑一般放置css,js,fonts等靜態(tài)文件,前端html中采用/static/js/xxx或/static/css/xxx等相對(duì)路徑的方式引用
  13.   router.StaticFS("/more_static", http.Dir("./")) //將本地文件樹(shù)結(jié)構(gòu)映射到前端, 通過(guò)瀏覽器可以訪(fǎng)問(wèn)本地文件系統(tǒng), 模擬訪(fǎng)問(wèn):http://localhost:8080/more_static
  14.   router.StaticFile("/logo.png", "./resources/logo.png")  //StaticFile提供單靜態(tài)單文件服務(wù), 模擬訪(fǎng)問(wèn):http://localhost:8080/log.png
  15.   // Listen and serve on 0.0.0.0:8080
  16.   router.Run(":8080")
  17. }

返回文件數(shù)據(jù)

 
 
 
 
  1. package main
  2. import (
  3.   "github.com/gin-contrib/cors"
  4.   "github.com/gin-gonic/gin"
  5.   "net/http"
  6. )
  7. func main() {
  8.   router := gin.Default()
  9.   router.Use(cors.Default())
  10.   router.GET("/local/file", func(c *gin.Context) {
  11.     c.File("./main.go")
  12.   })
  13.   // A FileSystem implements access to a collection of named files.
  14.   // The elements in a file path are separated by slash ('/', U+002F)
  15.   // characters, regardless of host operating system convention.
  16.   // FileSystem接口, 要求實(shí)現(xiàn)文件的訪(fǎng)問(wèn)的方法, 提供文件訪(fǎng)問(wèn)服務(wù)根路徑的HTTP處理器
  17.   var fs http.FileSystem = http.Dir("./")  //將本地目錄作為文件服務(wù)根路徑
  18.   router.GET("/fs/file", func(c *gin.Context) {
  19.     c.FileFromFS("main.go", fs)  //將文件服務(wù)系統(tǒng)下的文件數(shù)據(jù)返回
  20.   })
  21.   router.Run(":8080")
  22. }
  23. /*
  24. 模擬訪(fǎng)問(wèn)文件數(shù)據(jù):
  25. curl http://localhost:8080/local/file
  26. 模擬訪(fǎng)問(wèn)文件系統(tǒng)下的文件數(shù)據(jù):
  27. curl http://localhost:8080/fs/file
  28. */

用文件讀出器提供文件數(shù)據(jù)服務(wù)

 
 
 
 
  1. package main
  2. import (
  3.   "github.com/gin-gonic/gin"
  4.   "net/http"
  5. )
  6. func main() {
  7.   router := gin.Default()
  8.   router.GET("/someDataFromReader", func(c *gin.Context) {
  9.     response, err := http.Get("https://raw.githubusercontent.com/gin-gonic/logo/master/color.png")
  10.     if err != nil || response.StatusCode != http.StatusOK {  //請(qǐng)求鏈接中的文件出現(xiàn)錯(cuò)誤時(shí), 直接返回服務(wù)不可用
  11.       c.Status(http.StatusServiceUnavailable)
  12.       return
  13.     }
  14.     reader := response.Body  //用響應(yīng)體內(nèi)容構(gòu)造一個(gè)文件讀出器
  15.     defer reader.Close()
  16.     contentLength := response.ContentLength
  17.     contentType := response.Header.Get("Content-Type")
  18.     extraHeaders := map[string]string{
  19.       "Content-Disposition": `attachment; filename="gopher.png"`,
  20.     }
  21.     // DataFromReader writes the specified reader into the body stream and updates the HTTP code.
  22.     // func (c *Context) DataFromReader(code int, contentLength int64, contentType string, reader io.Reader, extraHeaders map[string]string) {}
  23.     // DataFromReader方法將指定的讀出器reader中的內(nèi)容, 寫(xiě)入http響應(yīng)體流中, 并更新響應(yīng)碼, 響應(yīng)頭信息等
  24.     c.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders)
  25.   })
  26.   router.Run(":8080")
  27. }
  28. /*
  29. 模擬訪(fǎng)問(wèn):
  30. curl http://localhost:8080/someDataFromReader
  31. */

HTML渲染

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

 
 
 
 
  1. package main
  2. import (
  3.   "github.com/gin-gonic/gin"
  4.   "net/http"
  5. )
  6. func main() {
  7.   router := gin.Default()
  8.   //LoadHTMLGlob方法以glob模式加載匹配的HTML文件, 并與HTML渲染器結(jié)合
  9.   router.LoadHTMLGlob("templates/*")
  10.   //router.LoadHTMLFiles("templates/template1.html", "templates/template2.html")
  11.   router.GET("/index", func(c *gin.Context) {
  12.     //HTML方法設(shè)置響應(yīng)碼, 模板文件名, 渲染替換模板中的值, 設(shè)置響應(yīng)內(nèi)容類(lèi)型Content-Type "text/html"
  13.     c.HTML(http.StatusOK, "index.tmpl", gin.H{
  14.       "title": "Main website",
  15.     })
  16.   })
  17.   router.Run(":8080")
  18. }
  19. /*
  20. 模擬測(cè)試:
  21. curl http://localhost:8080/index
  22. */

增加模板文件, templates/index.tmpl

 
 
 
 
  1.   

  2.     {{ .title }}
  3.   

 使用不同文件夾下的相同文件名的模板文件

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

posts目錄下添加模板文件, templates/posts/index.tmpl

 
 
 
 
  1. {{ define "posts/index.tmpl" }}
  2.   {{ .title }}
  3. Using posts/index.tmpl

  4. {{ end }}

 users目錄下添加模板文件, templates/users/index.tmpl

 
 
 
 
  1. {{ define "users/index.tmpl" }}
  2.   {{ .title }}
  3. Using users/index.tmpl

  4. {{ end }}

 自定義模板渲染器

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

 
 
 
 
  1. package main
  2. import (
  3.   "github.com/gin-gonic/gin"
  4.   "html/template"
  5.   "net/http"
  6. )
  7. func main() {
  8.   router := gin.Default()
  9.   //template.ParseFiles(文件1,文件2...)創(chuàng)建一個(gè)模板對(duì)象, 然后解析一組模板,使用文件名作為模板的名字
  10.   // Must方法將模板和錯(cuò)誤進(jìn)行包裹, 返回模板的內(nèi)存地址 一般用于變量初始化,比如:var t = template.Must(template.New("name").Parse("html"))
  11.   html := template.Must(template.ParseFiles("file1", "file2"))
  12.   router.SetHTMLTemplate(html) //關(guān)聯(lián)模板和HTML渲染器
  13.   router.GET("/index", func(c *gin.Context) {
  14.     //HTML方法設(shè)置響應(yīng)碼, 模板文件名, 渲染替換模板中的值, 設(shè)置響應(yīng)內(nèi)容類(lèi)型Content-Type "text/html"
  15.     c.HTML(http.StatusOK, "file1", gin.H{
  16.       "title": "Main website",
  17.     })
  18.   })
  19.   router.Run(":8080")
  20. }

自定義分隔符

你可以自定義分隔符, 模板中默認(rèn)的分隔符是{{ }}, 我們也可以修改, 比如下面增加一對(duì)中括號(hào)

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

自定義模板方法

詳見(jiàn) 示例代碼.

模板中與后端都定義好模板方法, 模板渲染時(shí)執(zhí)行該方法, 類(lèi)似過(guò)濾器方法, 比如時(shí)間格式化操作

 
 
 
 
  1. package main
  2. import (
  3.   "fmt"
  4.   "html/template"
  5.   "net/http"
  6.   "time"
  7.   "github.com/gin-gonic/gin"
  8. )
  9. func formatAsDate(t time.Time) string {
  10.   year, month, day := t.Date()  //Date方法返回年,月,日
  11.   return fmt.Sprintf("%d%02d/%02d", year, month, day)  //格式化時(shí)間
  12. }
  13. func main() {
  14.   router := gin.Default()
  15.   router.Delims("{[{", "}]}") //自定義模板中的左右分隔符
  16.   //SetFuncMap方法用給定的template.FuncMap設(shè)置到Gin引擎上, 后面模板渲染時(shí)會(huì)調(diào)用同名方法
  17.   //FuncMap是一個(gè)map,鍵名關(guān)聯(lián)方法名, 鍵值關(guān)聯(lián)方法, 每個(gè)方法必須返回一個(gè)值, 或者返回兩個(gè)值,其中第二個(gè)是error類(lèi)型
  18.   router.SetFuncMap(template.FuncMap{
  19.     "formatAsDate": formatAsDate,
  20.   })
  21.   router.LoadHTMLFiles("./testdata/template/raw.tmpl") //加載單個(gè)模板文件并與HTML渲染器關(guān)聯(lián)
  22.   router.GET("/raw", func(c *gin.Context) {
  23.     c.HTML(http.StatusOK, "raw.tmpl", gin.H{
  24.       "now": time.Date(2017, 07, 01, 0, 0, 0, 0, time.UTC),
  25.     })
  26.   })
  27.   router.Run(":8080")
  28. }
  29. /*
  30. 模擬測(cè)試:
  31. curl http://localhost:8080/raw
  32. */

定義模板文件: raw.tmpl

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

時(shí)間格式化結(jié)果:

 
 
 
 
  1. Date: 2017/07/01

多個(gè)模板

Gin默認(rèn)只使用一個(gè)html.Template模板引擎, 也可以參考多模板渲染器使用類(lèi)似Go1.6的塊級(jí)模板block template功能.

模板相關(guān)詳情請(qǐng)參考官方template包

參考文檔

Gin官方倉(cāng)庫(kù):https://github.com/gin-gonic/gin


文章名稱(chēng):GolangGinWeb框架7-靜態(tài)文件/模板渲染
文章路徑:http://www.dlmjj.cn/article/dhippjo.html