Gin框架使用(3)|青训营笔记

451 阅读1分钟

静态文件

func main() {
    router := gin.Default()
    //访问`localhost:8080/assets/{file}`可获取`./assets`目录下的`file`文件
    router.Static("/assets", "./assets") 
    //访问`localhost:8080/static/{file}`可获取`./static`目录下的`file`文件
    router.StaticFS("/more_static", http.Dir("my_file_system"))
    //访问`localhost:8080/favicon.ico`可获取当前目录下的`favicon.ico`文件
    router.StaticFile("/favicon.ico", "./resources/favicon.ico")
    router.StaticFileFS("/more_favicon.ico", "more_favicon.ico", http.Dir("my_file_system"))

    // Listen and serve on 0.0.0.0:8080
    router.Run(":8080")
}

HTML模版

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

在模版中取数据

<html>
    <h1>
        {{ .title }}
    </h1>
</html>

自定义模版函数

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

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

Gin 默认只允许使用一个 html.Template。

多模板渲染

package main

import (
    "github.com/gin-contrib/multitemplate"
    "github.com/gin-gonic/gin"
    "path/filepath"
)

func createMyRender() multitemplate.Renderer {
    r := multitemplate.NewRenderer()
    basePath, _ := filepath.Abs("templates")
    r.AddFromFiles("index", basePath + `\base.html`, basePath + `\index.html`)
    r.AddFromFiles("article", "templates/base.html", "templates/index.html", "templates/article.html")
    return r
}

func main() {
    router := gin.Default()
    router.HTMLRender = createMyRender()
    router.GET("/", func(c *gin.Context) {
            c.HTML(200, "index", gin.H{
                    "title": "Html5 Template Engine",
            })
    })
    router.GET("/article", func(c *gin.Context) {
            c.HTML(200, "article", gin.H{
                    "title": "Html5 Article Engine",
            })
    })
    router.GET("/json", func(context *gin.Context) {
            context.String(200, "OK")
    })

    router.Run()
}


package main

import (
    "github.com/gin-contrib/multitemplate"
    "github.com/gin-gonic/gin"
    "path/filepath"
)

func main() {
    router := gin.Default()
    router.HTMLRender = loadTemplates("./templates")
    router.GET("/", func(c *gin.Context) {
            c.HTML(200, "index.html", gin.H{
                    "title": "Welcome!",
            })
    })
    router.GET("/article", func(c *gin.Context) {
            c.HTML(200, "article.html", gin.H{
                    "title": "Html5 Article Engine",
            })
    })
    router.GET("/login", func(context *gin.Context) {
            context.HTML(200, "login.html", gin.H{
                    "title": "Login",
            })
    })

    router.Run()
}

func loadTemplates(templatesDir string) multitemplate.Renderer {
    r := multitemplate.NewRenderer()

    adminLayouts, err := filepath.Glob(templatesDir + "/layouts/base_admins.html")
    if err != nil {
            panic(err.Error())
    }
    adminInclude, err := filepath.Glob(templatesDir + "/admins/*.html")
    if err != nil {
            panic(err.Error())
    }
    // Generate our templates map from our layouts/ and articles/ directories
    for _, include := range adminInclude {
            layoutCopy := make([]string, len(adminLayouts))
            copy(layoutCopy, adminLayouts)
            files := append(layoutCopy, include)
            r.AddFromFiles(filepath.Base(include), files...)
    }

    articleLayouts, err := filepath.Glob(templatesDir + "/layouts/base_articles.html")
    if err != nil {
            panic(err.Error())
    }
    articleInclude, err := filepath.Glob(templatesDir + "/articles/*.html")
    if err != nil {
            panic(err.Error())
    }
    // Generate our templates map from our layouts/ and articles/ directories
    for _, include := range articleInclude {
            layoutCopy := make([]string, len(articleLayouts))
            copy(layoutCopy, articleLayouts)
            files := append(layoutCopy, include)
            r.AddFromFiles(filepath.Base(include), files...)
    }

    return r
}

重定向

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