github.com/qiuhoude/go-web@v0.0.0-20220223060959-ab545e78f20d/blogweb_gin/controllers/login_controller.go (about)

     1  package controllers
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/gin-contrib/sessions"
     6  	"github.com/gin-gonic/gin"
     7  
     8  	"github.com/qiuhoude/go-web/blogweb_gin/logs"
     9  	"github.com/qiuhoude/go-web/blogweb_gin/models"
    10  	"github.com/qiuhoude/go-web/blogweb_gin/utils"
    11  	"net/http"
    12  )
    13  
    14  func LoginGet(c *gin.Context) {
    15  	//返回html
    16  	c.HTML(http.StatusOK, "login.html", gin.H{"title": "登录页"})
    17  }
    18  
    19  //登录
    20  func LoginPost(c *gin.Context) {
    21  	//获取表单信息
    22  	username := c.PostForm("username")
    23  	password := c.PostForm("password")
    24  	logs.Info.Println("username:", username, ",password:", password)
    25  
    26  	id := models.QueryUserWithParam(username, utils.MD5(password))
    27  	fmt.Println("id:", id)
    28  	if id > 0 {
    29  		/*
    30  			设置了session后悔将数据处理设置到cookie,然后再浏览器进行网络请求的时候回自动带上cookie
    31  			因为我们可以通过获取这个cookie来判断用户是谁,这里我们使用的是session的方式进行设置
    32  		*/
    33  		session := sessions.Default(c)
    34  		session.Set(SessionStoreKey, username)
    35  		session.Save()
    36  		c.JSON(http.StatusOK, gin.H{"code": 1, "message": "登录成功"})
    37  	} else {
    38  		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "登录失败"})
    39  	}
    40  }