diff --git a/common/database.go b/common/database.go new file mode 100644 index 0000000..fa2bffe --- /dev/null +++ b/common/database.go @@ -0,0 +1,44 @@ +package common + +import ( + "fmt" + + "github.com/zggsong/gin-vue-demo/model" + "gorm.io/driver/mysql" + "gorm.io/gorm" +) + +var DB *gorm.DB + +func init() { + // 配置 MySQL 连接参数 + username := "root" // 账号 + password := "jiaobaba" // 密码 + host := "127.0.0.1" // 数据库地址,可以是Ip或者域名 + port := 3306 // 数据库端口 + Dbname := "gin-vue-demo" // 数据库名 + timeout := "10s" // 连接超时,10秒 + + // 拼接下 dsn 参数, dsn 格式可以参考上面的语法,这里使用 Sprintf 动态拼接 dsn 参数,因为一般数据库连接参数,我们都是保存在配置文件里面,需要从配置文件加载参数,然后拼接 dsn。 + dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local&timeout=%s", + username, + password, + host, + port, + Dbname, + timeout) + + // 连接 Mysql, 获得 DB 类型实例,用于后面的数据库读写操作。 + db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{}) + if err != nil { + panic("连接数据库失败, error=" + err.Error()) + } + + db.AutoMigrate(&model.User{}) + + DB = db +} + +func GetDB() *gorm.DB { + return DB +} diff --git a/controller/register.go b/controller/register.go new file mode 100644 index 0000000..a99996e --- /dev/null +++ b/controller/register.go @@ -0,0 +1,71 @@ +package controller + +import ( + "log" + "net/http" + + "github.com/gin-gonic/gin" + "github.com/zggsong/gin-vue-demo/common" + "github.com/zggsong/gin-vue-demo/model" + "github.com/zggsong/gin-vue-demo/util" + "gorm.io/gorm" +) + +func Register(ctx *gin.Context) { + DB := common.GetDB() + // 获取参数 + name := ctx.Query("name") + telephone := ctx.Query("telephone") + password := ctx.Query("password") + + // 数据验证 + if len(telephone) != 11 { + ctx.JSON(http.StatusUnprocessableEntity, gin.H{ + "code": http.StatusUnprocessableEntity, + "message": "手机号必须是11位", + }) + return + } + if len(password) < 6 { + ctx.JSON(http.StatusUnprocessableEntity, gin.H{ + "code": http.StatusUnprocessableEntity, + "message": "密码必须大于6位", + }) + return + } + // 如果名字为空则返回10为随机字符串 + if name == "" { + name = util.RandomString(10) + } + + log.Println(name, telephone, password) + + // 判断手机号是否存在 + if isExistTelephone(DB, telephone) { + ctx.JSON(http.StatusUnprocessableEntity, gin.H{ + "code": http.StatusUnprocessableEntity, + "message": "手机号已存在", + }) + return + } + + // 创建用户 + newUser := model.User{ + Name: name, + Telephone: telephone, + Password: password, + } + DB.Create(&newUser) + + // 返回结果 + ctx.JSON(200, gin.H{ + "code": http.StatusOK, + "message": "注册成功", + }) +} + +func isExistTelephone(db *gorm.DB, telephone string) bool { + var user model.User + db.Where("telephone = ?", telephone).First(&user) + return user.ID != 0 +} diff --git a/main.go b/main.go index 9a99d6a..f34c945 100644 --- a/main.go +++ b/main.go @@ -1,124 +1,15 @@ package main import ( - "fmt" - "log" - "math/rand" - "net/http" - "time" - "github.com/gin-gonic/gin" - "gorm.io/driver/mysql" - "gorm.io/gorm" + "github.com/zggsong/gin-vue-demo/router" ) -type User struct { - gorm.Model - Name string `json:"name";gorm:"type:varchar(20);not null` - Telephone string `json:"telephone";gorm:"type:varchar(11);not null;unique"` - Password string `json:"password";gorm:"type:varchar(20);not null"` -} - func main() { - db := initDB() + // DB := common.GetDB() + // defert DB.Close() r := gin.Default() - r.POST("/api/auth/register", func(ctx *gin.Context) { - // 获取参数 - name := ctx.Query("name") - telephone := ctx.Query("telephone") - password := ctx.Query("password") - - // 数据验证 - if len(telephone) != 11 { - ctx.JSON(http.StatusUnprocessableEntity, gin.H{ - "code": http.StatusUnprocessableEntity, - "message": "手机号必须是11位", - }) - return - } - if len(password) < 6 { - ctx.JSON(http.StatusUnprocessableEntity, gin.H{ - "code": http.StatusUnprocessableEntity, - "message": "密码必须大于6位", - }) - return - } - // 如果名字为空则返回10为随机字符串 - if name == "" { - name = RandomString(10) - } - - log.Println(name, telephone, password) - - // 判断手机号是否存在 - if isExistTelephone(db, telephone) { - ctx.JSON(http.StatusUnprocessableEntity, gin.H{ - "code": http.StatusUnprocessableEntity, - "message": "手机号已存在", - }) - return - } - - // 创建用户 - newUser := User{ - Name: name, - Telephone: telephone, - Password: password, - } - db.Create(&newUser) - - // 返回结果 - ctx.JSON(200, gin.H{ - "code": http.StatusOK, - "message": "注册成功", - }) - }) + r = router.CollectRoute(r) panic(r.Run("127.0.0.1:8080")) } - -// 随机字符串 -func RandomString(length int) string { - str := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" - bytes := []byte(str) - result := []byte{} - r := rand.New(rand.NewSource(time.Now().UnixNano())) - for i := 0; i < length; i++ { - result = append(result, bytes[r.Intn(len(bytes))]) - } - return string(result) -} - -func initDB() *gorm.DB { - // 配置 MySQL 连接参数 - username := "root" // 账号 - password := "jiaobaba" // 密码 - host := "127.0.0.1" // 数据库地址,可以是Ip或者域名 - port := 3306 // 数据库端口 - Dbname := "gin-vue-demo" // 数据库名 - timeout := "10s" // 连接超时,10秒 - - // 拼接下 dsn 参数, dsn 格式可以参考上面的语法,这里使用 Sprintf 动态拼接 dsn 参数,因为一般数据库连接参数,我们都是保存在配置文件里面,需要从配置文件加载参数,然后拼接 dsn。 - dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local&timeout=%s", - username, - password, - host, - port, - Dbname, - timeout) - - // 连接 Mysql, 获得 DB 类型实例,用于后面的数据库读写操作。 - db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{}) - if err != nil { - panic("连接数据库失败, error=" + err.Error()) - } - - db.AutoMigrate(&User{}) - return db -} - -func isExistTelephone(db *gorm.DB, telephone string) bool { - var user User - db.Where("telephone = ?", telephone).First(&user) - return user.ID != 0 -} diff --git a/model/user.go b/model/user.go new file mode 100644 index 0000000..fccdabc --- /dev/null +++ b/model/user.go @@ -0,0 +1,10 @@ +package model + +import "gorm.io/gorm" + +type User struct { + gorm.Model + Name string `json:"name";gorm:"type:varchar(20);not null` + Telephone string `json:"telephone";gorm:"type:varchar(11);not null;unique"` + Password string `json:"password";gorm:"type:varchar(20);not null"` +} diff --git a/router/router.go b/router/router.go new file mode 100644 index 0000000..fbf1f4a --- /dev/null +++ b/router/router.go @@ -0,0 +1,11 @@ +package router + +import ( + "github.com/gin-gonic/gin" + "github.com/zggsong/gin-vue-demo/controller" +) + +func CollectRoute(r *gin.Engine) *gin.Engine { + r.POST("/api/auth/register", controller.Register) + return r +} diff --git a/util/util.go b/util/util.go new file mode 100644 index 0000000..2909308 --- /dev/null +++ b/util/util.go @@ -0,0 +1,18 @@ +package util + +import ( + "math/rand" + "time" +) + +// 随机字符串 +func RandomString(length int) string { + str := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" + bytes := []byte(str) + result := []byte{} + r := rand.New(rand.NewSource(time.Now().UnixNano())) + for i := 0; i < length; i++ { + result = append(result, bytes[r.Intn(len(bytes))]) + } + return string(result) +}