go-gin (youtebu自学) - 第七课 -- HTML

HTML

  • 新建文件夹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的接口groupserver.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
    
    结果
    在这里插入图片描述