Full stack blog development add rendering

Keywords: Go

Original link

https://llfc.club/category?catid=20RbopkFO8nsJafpgCwwxXoCWAs#!aid/21lVoQbhTZo83drdNp10Iv2WOfc

Objectives of this section

In the previous section, we added the routing of the home page and the html template of the home page. In this section, we return a template with parameter rendering, add the load data from the database to the html, and set the middleware. When there is a request to access the admin background, judge whether it contains a login cookie. If there is no login, return to the login page
Source address:
https://github.com/secondtonone1/bstgo-blog

Add Middleware

gin supports rich middleware functions. First, we implement a cross domain access function and the function of detecting login cookie s

func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method
 
		c.Header("Access-Control-Allow-Origin", "*")
		c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token")
		c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE") //All cross domain requestors supported by the server
		c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
		c.Header("Access-Control-Allow-Credentials", "true")
 
		//Release all OPTIONS methods
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}
		// Processing requests
		c.Next()
	}
}
 
func GroupRouterAdminMiddle(c *gin.Context) {
 
	log.Println("=====================admin group router middle")
	//Determine whether there is a session in the cookie_ id
	sessionId, err := c.Cookie(model.CookieSession)
	if err != nil {
		//If there is no sessionId, return to the login page
		log.Println("no cookie sessionId ,return login")
		c.HTML(http.StatusOK, "admin/login.html", nil)
		c.Abort()
		return
	}
	sessionData, err := mongocli.GetSessionById(sessionId)
	if err != nil {
		log.Println("get sessionid ", sessionId, "failed, return login")
		c.HTML(http.StatusOK, "admin/login.html", nil)
		c.Abort()
		return
	}
	log.Println("session data is : ", sessionData)
	c.Next()
}
 
func CheckLogin(c *gin.Context) {
	log.Println("check login midware")
	//Determine whether there is a session in the cookie_ id
	sessionId, err := c.Cookie(model.CookieSession)
	if err != nil {
		//If there is no sessionId, return to the login page
		log.Println("no cookie sessionId ,return login")
		baseRsp := model.BaseRsp{}
		baseRsp.Code = model.ERR_NO_LOGIN
		baseRsp.Msg = model.MSG_NO_LOGIN
		c.JSON(http.StatusOK, baseRsp)
		c.Abort()
		return
	}
	sessionData, err := mongocli.GetSessionById(sessionId)
	if err != nil {
		log.Println("get sessionid ", sessionId, "failed, return login")
		baseRsp := model.BaseRsp{}
		baseRsp.Code = model.ERR_NO_LOGIN
		baseRsp.Msg = model.MSG_NO_LOGIN
		c.JSON(http.StatusOK, baseRsp)
		c.Abort()
		return
	}
	log.Println("session data is : ", sessionData)
	c.Next()
}

Both CheckLogin and grouprouteradmiddle are middleware used to detect login information. Only one returns json and the other returns html template
Cors supports cross domain access
Then modify the previous main function to support middleware

func main() {
	mongocli.MongoInit()
	router := gin.Default()
	router.Use(Cors()) //Default cross domain
	//Load template file
	router.LoadHTMLGlob("views/**/*")
	//Set resource sharing directory
	router.StaticFS("/static", http.Dir("./public"))
	//Users browse the home page
	router.GET("/home", home.Home)
	//Users browse your categories
	router.GET("/category", home.Category)
 
	//Users browse individual articles
	router.GET("/articlepage", home.ArticlePage)
 
	//admin login page
	router.GET("/admin/login", admin.Login)
	//admin login submission
	router.POST("/admin/loginsub", admin.LoginSub)
 
	// Create and manage routing groups
	adminGroup := router.Group("/admin")
	adminGroup.Use(GroupRouterAdminMiddle)
	{
		//Management home page
		adminGroup.GET("/", admin.Admin)
		//Management classification
		adminGroup.POST("/category", admin.Category)
	}
 
	// Article editing and publishing
	router.POST("admin/pubarticle", CheckLogin, admin.ArticlePub)
 
	router.Run(":8080")
	mongocli.MongoRelease()
}

  

mongo's initialization function is called in the main function, and mongo's release function is called at the end
router.Use(Cors()) supports cross domain access for all routes
Admingroup. Use (grouprouteradmiddle) performs login verification on the groups accessed by / admin and returns html
CheckLogin performs login verification on the route of admin/pubarticle and returns json results

Let the page display background content

Before, the html page we returned was static. Now we dynamically return the page through the template rendering function of gin. The content of the page is the data queried by the background mongo.
We return the rendering structure of the page in the request article page logic

func ArticlePage(c *gin.Context) {
	id := c.Query("id")
	log.Println("id is ", id)
	if id == "" {
		c.HTML(http.StatusOK, "home/errorpage.html", "invalid page request , id is null, after 2 seconds return to home")
		return
	}
 
	article, err := mongocli.GetArticleId(id)
 
	if err != nil {
		c.HTML(http.StatusOK, "home/errorpage.html", "get article failed, after 2 seconds return to home")
		return
	}
 
	articleR := &model.ArticlePageR{}
	articleR.Author = article.Author
	articleR.Cat = article.Cat
	articleR.Content = template.HTML(article.Content)
	createtm := time.Unix(article.CreateAt, 0)
	articleR.CreateAt = createtm.Format("2006-01-02 15:04:05")
 
	lasttm := time.Unix(article.LastEdit, 0)
	articleR.LastEdit = lasttm.Format("2006-01-02 15:04:05")
	articleR.Id = article.Id
	articleR.Index = article.Index
	articleR.LoveNum = article.LoveNum
	articleR.ScanNum = article.ScanNum
	articleR.Subcat = article.Subcat
	articleR.Subtitle = article.Subtitle
	articleR.Title = article.Title
 
	c.HTML(http.StatusOK, "home/articlepage.html", articleR)
}

Get the article structure from mongo, pass in the html template, render and return. The article structure is defined in the model module

//Article structure
type Article struct {
	Id       string `bson:"id"`
	Cat      string `bson: "cat"`
	Title    string `bson: "title"`
	Content  string `bson: "content"`
	Subcat   string `bson: "subcat"`
	Subtitle string `bson: "subtitle"`
	ScanNum  int    `bson:"scannum"`
	LoveNum  int    `bson:"lovenum`
	CreateAt int64  `bson:"createdAt"`
	LastEdit int64  `bson:"lastedit"`
	Author   string `bson:"author"`
	Index    int    `bson:"index"`
}

  

mongo's addition, deletion, modification and query have been explained in previous articles, which will not be introduced here.

test result

Execute command

go run ./main.go

Then enter localhost:8080/articlepage?id=21M9WdW62KbVXXrlPfZhPOCFP31 on the console
You can see the following effects

 

 

Visit the background page localhost:8080/admin
When there is no login cookie, it will return to the login interface

 

Posted by Vidya_tr on Sun, 05 Dec 2021 08:29:07 -0800