使用Golang流行的web框架Gin渲染HTML模板页面的简单例子

Gin是Golang最流行的web框架之一。我之前已经写过如何使用Golang基础模板包渲染HTML页面。使用Gin渲染HTML模板更加简单。

为了使工作流更加顺畅,尝试新的想法并进行调试,我还决定使用Codegangsta的自动重载工具Gin。

安装Gin

安装Gin HTTP web框架就像安装大多数(如果不是所有)Golang包一样简单:

go get -u github.com/gin-gonic/gin
Gin 代码
package main

import (
    "html/template"
    "net/http"
    "strings"

    "github.com/gin-gonic/gin"
)

func main() {
    router := gin.Default()
    router.SetFuncMap(template.FuncMap{
        "upper": strings.ToUpper,
    })
    router.Static("/assets", "./assets")
    router.LoadHTMLGlob("templates/*.html")

    router.GET("/", func(c *gin.Context) {
        c.HTML(http.StatusOK, "index.html", gin.H{
            "content": "This is an index page...",
        })
    })

    router.GET("/about", func(c *gin.Context) {
        c.HTML(http.StatusOK, "about.html", gin.H{
            "content": "This is an about page...",
        })
    })
    router.Run("localhost:8080")
}

引入的包

在第4到7行,我们引入了一些包:

html/templateFuncMap()net/httpstringsFuncMapupper

main()函数

router
SetFuncMap()upperstrings.ToUpper()
./assets
Static()
template/*.htmlLoadHTMLGlob().html/template
/GETOKgin.H{}index.htmlcontent
/aboutGETabout.html
localhost8080
模板和目录结构

下面你可以找到本例中使用的四个模板。这些模板每个都需要在自己的文件中。每段代码之前都有文件名。

html/template
// header.html
{{define "header.html"}}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="/assets/bulma.min.css">
    <title></title>
</head>
<body>
<div class="container">
<br><br>
{{end}}
  

// footer.html
{{define "footer.html"}}
</div>
</body>
</html>
{{end}}


// index.html
{{template "header.html"}}
<h1 class="title">
    INDEX PAGE
</h1>
<p>{{ .content }}</p>
{{template "footer.html"}}


// about.html
{{template "header.html"}}
<h1 class="title">
    ABOUT PAGE
</h1>
<p>{{ .content | upper}}</p>
{{template "footer.html"}}
自动重载Gin

如前所述,我在开发时使用codegangsta/gin工具来自动重载gin。这使得在浏览器中检查我们代码的结果变得更加容易。当我们改变了代码,无需停止当前的可执行文件,重新构建和运行它,就可以做到这一点。

以下是Github页面上对这个工具的描述:

gingingingin

安装codegangsta/gin

go get github.com/codegangsta/gin

运行codegangsta/gin

gin -i --appPort 8080 --port 3000 run main.go
localhost80803000

关于运行代码的注意事项

在从命令行运行代码之前,你可能需要运行以下命令:

go mod init
go mod tidy
在网页浏览器中检查结果

在浏览器的URL字段中输入以下内容以检查代码的结果:

localhost:3000/

…对于索引页面,和…

localhost:3000/about

对于关于页面。

列表清单

请记住,始终保持学习的态度,并享受编码的乐趣!祝您编码愉快!

如果你喜欢我的文章,点赞,关注,转发!