使用gin实现简单的注册和登录功能

一、前言

使用了gorm操作数据库,后端基于gin框架,只是一个简单的注册和登录与数据库交互的后端实现例子。

二、目录结构

 -templates
   --regist.html
   --login.html
 -main.go

三、代码

regist.html

点击查看代码

<!DOCTYPE html>
<html>
<head>
    <title>注册</title>
</head>
<body>
    <h1>用户注册</h1>
    <form action="/register" method="POST">
        <label for="username">用户名:</label>
        <input type="text" name="username" required><br><br>

        <label for="password">密码:</label>
        <input type="password" name="password" required><br><br>

        <label for="email">邮箱:</label>
        <input type="text" name="email" required><br><br>

        <label for="age">年龄:</label>
        <input type="text" name="age" required><br><br>

        <button type="submit">注册</button>
    </form>
        <!-- 错误信息展示 -->
        {{ if .error }}
        <p style="color:red">{{ .error }}</p>
    {{ end }}
</body>
</html>

login.html

点击查看代码

<!DOCTYPE html>
<html>
<head>
    <title>登录</title>
</head>
<body>
    <h1>用户登录</h1>
    <form action="/login" method="POST">
        <label for="username">用户名:</label>
        <input type="text" name="username" required><br><br>

        <label for="password">密码:</label>
        <input type="password" name="password" required><br><br>

        <button type="submit">登录</button>
    </form>
            <!-- 错误信息展示 -->
            {{ if .error }}
            <p style="color:red">{{ .error }}</p>
        {{ end }}
                    <!-- 成功信息展示 -->
                    {{ if .success }}
                    <p style="color:red">{{ .success }}</p>
                {{ end }}
</body>
</html>

main.go

点击查看代码

package main

import (
	"log"
	"net/http"
	_ "github.com/go-sql-driver/mysql"

	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
)
var db *gorm.DB
var err error
//定义数据表
type User struct {
	gorm.Model
	Username string `gorm:"unique" json:"username"`
	Password string `json:"password"`
	Age string `json:"age"`
	Email string `json:"email"`
}
//连接数据库,使用gorm
func ConDB(){
	dsn :="root:root@(127.0.0.1:3306)/mydb?charset=utf8mb4&parseTime=True&loc=Local"
	db,err = gorm.Open("mysql",dsn)
	if err!=nil{
		log.Println(err)
	}

	//迁移数据表
	db.AutoMigrate(&User{})

}

func main() {
	//注册路由
	r := gin.Default()
	//连接数据库
	ConDB()

	//加载模版

	r.LoadHTMLGlob("templates/*")

	//注册路由,实现登录和注册,get获取页面,post提交数据
	r.GET("/register",ShowRegisterPage)
	r.POST("/register",Regist)
	//登录
	r.GET("/login",ShowLoginPage)
	r.POST("/login",Login)
	r.Run(":8080")

}

//注册页面
func ShowRegisterPage(c *gin.Context){
	c.HTML(http.StatusOK,"regist.html",nil)
}
//注册提交
func Regist(c *gin.Context) {
	//获取表单数据
	username := c.PostForm("username")
	password := c.PostForm("password")
	age		 := c.PostForm("age")
	email	 := c.PostForm("email")

	//查询用户是否存在
	user :=new(User) //初始化的user是默认id=0
	db.Where("username = ?",username).First(user)
	log.Println(*user)
	if user.ID !=0 {
		c.HTML(http.StatusCreated,"regist.html",gin.H{"error":"用户已存在"})
		return
	} else {
		newuser := User{
			Username: username,
			Password: password,
			Age: age,
			Email: email,
		}
		db.Create(&newuser)
		c.HTML(http.StatusOK,"login.html",gin.H{"success":"注册成功,请登录"})
	}

}
//登录界面
func ShowLoginPage(c *gin.Context){
	c.HTML(http.StatusOK,"login.html",nil)
}
//登录路由
func Login(c *gin.Context){
	//获取数据
	username := c.PostForm("username")
	password := c.PostForm("password")

	//查询用户并验证密码
	var loginuser User
	db.First(&loginuser,"username = ?",username)
	if loginuser.ID ==0 {
		c.HTML(http.StatusBadRequest,"login.html",gin.H{"error":"用户不存在!"})
		return
	}else {
		// log.Panicln("first:-+++++>>>",loginuser)
		// log.Panicln("find::->>>>>",loginuser)
		if password == loginuser.Password {
			c.JSON(http.StatusOK,"登录成功!")
		} else {

			c.HTML(http.StatusBadRequest,"login.html",gin.H{"error":"用户名或密码错误"})
			
		}
	}

}