目录结构:
tree .
.
├── Go-Protobuf-Tips
├── renderingDataMain.go
├── static
│ └── 01.jpeg
├── templates
│ ├── posts
│ │ └── index.tmpl
│ └── users
│ └── index.tmpl
模板文件内容:
package main
index.tmpl
{{ define "users/index.tmpl"}}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{.title}}</title>
</head>
<body>
<p>Using users/index.tmpl</p>
</body>
</html>
{{end}}
index.tmpl
{{ define "posts/index.tmpl"}}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{.title}}</title>
</head>
<body>
<p>Using users/index.tmpl</p>
</body>
</html>
{{end}}
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main(){
e := gin.Default()
//静态资源映射
e.Static("/static","./static")
type User struct {
Name string `json:"name"`
Password string `json:"password"`
}
//渲染json数据
e.GET("/getUserJson", func(c *gin.Context) {
user := &User{
Name: "Jack",
Password: "jack1234",
}
c.JSON(http.StatusOK,user)
})
//渲染xml数据
e.GET("/getUserXML", func(c *gin.Context) {
user := &User{
Name: "Tom",
Password: "tom1234",
}
c.XML(http.StatusOK,user)
})
//渲染Html模板数据
e.LoadHTMLGlob("templates/**/*")
e.GET("/posts/index", func(c *gin.Context) {
c.HTML(http.StatusOK,"posts/index.tmpl",gin.H{
"title":"Posts",
})
})
e.GET("/users/index", func(c *gin.Context) {
c.HTML(http.StatusOK,"users/index.tmpl",gin.H{
"title":"Users",
})
})
e.Run(":9090")
}
gin框架渲染不同的类型的数据
最新推荐文章于 2022-10-24 12:09:17 发布