Gin+Gorm+PostGresSQL+Vue项目实战(2)

参考视频:【评论送书】Go语言 Gin+Vue 前后端分离实战 - OceanLearn_哔哩哔哩_bilibili

上一篇:Gin+Gorm+PostGresSQL+Vue项目实战(1)_代码骑士的博客-CSDN博客

一、项目重构:

项目文件夹结构:

二、代码分解:

database.go

package common

import (
	"log"
	"testGinAndVue01/model"

	_ "github.com/jinzhu/gorm/dialects/postgres"

	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/postgres"
	//"gorm.io/gorm"
)

var DB *gorm.DB

//数据库初始化
func InitDB() *gorm.DB {
	//连接数据库
	db, err := gorm.Open("postgres", "host=127.0.0.1 port=5432 user=postgres dbname=db2 password=123456 sslmode=disable")
	if err != nil {
		log.Println(err)
	} else {
		log.Println("连接成功!")
	}
	db.AutoMigrate(&model.User{}) //自动创建数据表User
	DB = db
	return db
}

//获取数据库实例
func GetDB() *gorm.DB {

	return DB
}

usercontroller.go

package controller

import (
	"log"
	"net/http"
	"testGinAndVue01/common"
	"testGinAndVue01/model"
	"testGinAndVue01/util"

	"github.com/gin-gonic/gin"
	//"gorm.io/gorm"
)

func Register(ctx *gin.Context) {
	//db := common.InitDB()
	db := common.GetDB()

	//获取参数
	name := ctx.PostForm("name")
	telephone := ctx.PostForm("telephone")
	password := ctx.PostForm("password")
	//数据验证
	if len(telephone) != 11 {
		ctx.JSON(http.StatusUnprocessableEntity, gin.H{"code": 422, "msg": "手机号必须是11位"})
		return
	}
	if len(password) < 6 {
		ctx.JSON(http.StatusUnprocessableEntity, gin.H{"code": 422, "msg": "密码至少6位"})
		return
	}
	//如果名称为空值就随机生成十位字符串
	if len(name) == 0 {
		name = util.RandomString(10)
	}

	log.Println(name, telephone, password)
	//判断手机号是否存在
	if isTelephoneExist_(telephone) {
		ctx.JSON(http.StatusUnprocessableEntity, gin.H{"code": 422, "msg": "该手机号已被注册"})
		return
	}
	//创建用户
	newUser := model.User{
		Name:      name,
		Telephone: telephone,
		Password:  password,
	}
	db.Create(&newUser)
	//返回结果
	ctx.JSON(http.StatusOK, gin.H{
		"msg": "注册成功!",
	})
}
func isTelephoneExist_(telephone string) bool {
	var user model.User
	db := common.GetDB()
	db.Where("telephone=?", telephone).First(&user)
	if user.ID != 0 {
		return true
	} else {
		return false
	}
}

user.go

package model

import "github.com/jinzhu/gorm"

type User struct {
	gorm.Model
	Name      string `gorm:"type:varchar(20);not null"`
	Telephone string `gorm:"type:varchar(11);not null;unique"`
	Password  string `gorm:"type:varchar(18);not null"`
}

routes.go

package router

import (
	"testGinAndVue01/controller"

	"github.com/gin-gonic/gin"
)

func CollectRoute(r *gin.Engine) *gin.Engine {
	r.POST("/api/auth/register", controller.Register)
	return r
}

util.go

package util

import (
	"math/rand"
	"time"
)

//随机生成名字
func RandomString(n int) string {
	var letters = []byte("dshugvrhilg12lg321hre13gv12312iefes")
	result := make([]byte, n)

	rand.Seed(time.Now().Unix())

	for i := range result {
		result[i] = letters[rand.Intn(len(letters))]
	}
	return string(result)
}

main.go

package main

import (
	"testGinAndVue01/common"
	"testGinAndVue01/router"

	_ "github.com/jinzhu/gorm/dialects/postgres"

	"github.com/gin-gonic/gin"
)

func main() {
	db := common.InitDB()
	defer db.Close()
	r := gin.Default()
	r = router.CollectRoute(r)
	r.Run(":8080")
}

三、测试:

Post请求:

后端:

数据库:

下一篇:(6条消息) Gin+Gorm+PostGresSQL+Vue项目实战(3)_代码骑士的博客-CSDN博客

猜你喜欢

转载自blog.csdn.net/qq_51701007/article/details/125042393
今日推荐