- 新建文件夹
template
- 新建文件
template/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
{{ template "header.html" }}
{{ template "footer.html" }}
</body>
</html>
- 新建文件
template/header.html
- 新建文件
template/footer.html
- 新建文件夹
asset
- 新建文件夹
asset/css
- 新建文件
asset/css/index.css
- 声明静态文件
server.go
...
server := gin.New()
server.Static("/css", "asset/css")
server.LoadHTMLGlob("template/*.html")
server.Use(gin.Recovery(), middleware.Logger(), middleware.BasicAuth(), ginDump.Dump())
...
- 写好
showAll()
方法,用于前端展示页面blog-controller.go
...
type BlogController interface {
FindAll() []entity.BlogEntity
Save(*gin.Context) error
ShowAll(*gin.Context)
}
...
func (bc *blogController) ShowAll(c *gin.Context) {
blogs := bc.bs.FindAll()
data := gin.H{
"title": "Blog Page",
"blogs": blogs,
}
c.HTML(http.StatusOK, "index.html", data)
}
...
- 将api与view的接口group
server.go
...
server.Use(gin.Recovery(), middleware.Logger(), middleware.BasicAuth(), ginDump.Dump())
apiGroup := server.Group("api")
{
apiGroup.GET("blogs", func(c *gin.Context) {
c.JSON(http.StatusOK, blogController.FindAll())
})
apiGroup.POST("blogs", func(c *gin.Context) {
err := blogController.Save(c)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
} else {
c.JSON(http.StatusCreated, gin.H{
"message": "blog Created!",
})
}
})
}
viewGroup := server.Group("view")
{
viewGroup.GET("blogs", blogController.ShowAll)
}
server.Run(":8080")
...
- 到html接受变量
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ .title }}</title>
</head>
<body>
{{ template "header.html" }}
{{ range .blogs }}
{{ .Title }}
{{ .Description }}
{{ .URL }}
{{ end }}
{{ template "footer.html" }}
</body>
</html>
- 运行
go run server.go
- 测试
先新增一个,后通过浏览器查看POST - localhost:8080/api/blogs
结果