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

     1  package controllers
     2  
     3  import (
     4  	"github.com/gin-gonic/gin"
     5  	"github.com/qiuhoude/go-web/blogweb_gin/logs"
     6  	"github.com/qiuhoude/go-web/blogweb_gin/models"
     7  	"github.com/qiuhoude/go-web/blogweb_gin/utils"
     8  	"net/http"
     9  	"time"
    10  )
    11  
    12  func RegisterGet(c *gin.Context) {
    13  	c.HTML(http.StatusOK, "register.html", gin.H{"title": "注册页"})
    14  }
    15  
    16  func RegisterPost(c *gin.Context) {
    17  	username := c.PostForm("username")
    18  	password := c.PostForm("password")
    19  	repassword := c.PostForm("repassword")
    20  	logs.Info.Println(username, password, repassword)
    21  
    22  	//注册之前先判断该用户名是否已经被注册,如果已经注册,返回错误
    23  	id := models.QueryUserWithUsername(username)
    24  	logs.Info.Println("id:", id)
    25  	if id > 0 {
    26  		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "用户名已经存在"})
    27  		return
    28  	}
    29  
    30  	//注册用户名和密码
    31  	//存储的密码是md5后的数据,那么在登录的验证的时候,也是需要将用户的密码md5之后和数据库里面的密码进行判断
    32  	password = utils.MD5(password)
    33  	logs.Info.Println("md5后:", password)
    34  
    35  	user := models.User{0, username, password, 0, time.Now().Unix()}
    36  	_, err := models.InsertUser(user)
    37  	if err != nil {
    38  		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "注册失败"})
    39  	} else {
    40  		c.JSON(http.StatusOK, gin.H{"code": 1, "message": "注册成功"})
    41  	}
    42  }