1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
| package main
import ( "fmt" "math/rand" "net/http" "time"
"github.com/e421083458/gorm" //https://gorm.io "github.com/gin-gonic/gin" _ "github.com/go-sql-driver/mysql" )
type User struct { gorm.Model Name string `gorm:"type:varchar(20);not null"` Telephone string `gorm:"varchar(110;not null;unique"` Password string `gorm:"size:255;not null"` }
func main() {
db := InitDb() defer db.Close()
r := gin.New() r.Use(gin.Logger())
r.Use(gin.Recovery())
r.POST("/api/auth/register", func(ctx *gin.Context) { //获取参数 name := ctx.PostForm("name") telephone := ctx.PostForm("telephone") password := ctx.PostForm("password")
//验证数据 if len(telephone) != 11 { ctx.JSON(http.StatusServiceUnavailable, gin.H{"code": 422, "msg": "手机号必须为11为"}) }
if len(password) < 6 { ctx.JSON(http.StatusUnprocessableEntity, gin.H{"code": 422, "msg": "密码不能少于6位"}) }
//名称如果没有传,则返回随机字符串 if len(name) == 0 { name = RandomString(10) } //判断手机号是否存在 if isTelephoneExist(db, telephone) { ctx.JSON(http.StatusUnprocessableEntity, gin.H{"code": 422, "msg": "用户已经存在"}) return }
//创建用户 newUser := User{ Name: name, Telephone: telephone, Password: password, } db.Create(&newUser)
//返回结果 ctx.JSON(200, gin.H{ "msg": "注册成功", }) })
panic(r.Run(":8099")) }
func isTelephoneExist(db *gorm.DB, telephone string) bool { var user User db.Where("telephone = ?", telephone).First(&user) if user.ID != 0 { return true }
return false }
//返回随机字符串 func RandomString(n int) string { var letters = []byte("iasdhjklfhascvxnjklasdfhjkasdfklasdfhnjklasdfjklasdfjklfasdsdfjk") result := make([]byte, n)
rand.Seed(time.Now().Unix())
for i := range result { result[i] = letters[rand.Intn(len(letters))] }
return string(result) }
func InitDb() *gorm.DB { driverName := "mysql" host := "127.0.0.1" port := "3306" database := "gin_vue_bs" username := "root" passwoed := "123456" charset := "utf8" args := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=true", username, passwoed, host, port, database, charset)
db, err := gorm.Open(driverName, args) if err != nil { panic("failed to connect database,err" + err.Error()) }
//创建数据表 db.AutoMigrate(&User{})
return db }
|