Go 语言框架 Gin 练习1
目錄
文章目錄
- 目錄
- 1 介紹
- 源碼下載
- 2 練習(xí)
- 效果演示
- 友情支持
1 介紹
Gin是一個(gè)golang的微框架,封裝比較優(yōu)雅,API友好,源碼注釋比較明確,具有快速靈活,容錯(cuò)方便等特點(diǎn)
對(duì)于golang而言,web框架的依賴要遠(yuǎn)比Python,Java之類的要小。自身的net/http足夠簡(jiǎn)單,性能也非常不錯(cuò)
借助框架開發(fā),不僅可以省去很多常用的封裝帶來(lái)的時(shí)間,也有助于團(tuán)隊(duì)的編碼風(fēng)格和形成規(guī)范
源碼下載
下載地址
2 練習(xí)
本次練習(xí)主要實(shí)現(xiàn)一個(gè)可以實(shí)現(xiàn)用戶注冊(cè)的后臺(tái)。
// main.go package mainimport ("log""math/rand""net/http""time""github.com/gin-gonic/gin"_ "github.com/go-sql-driver/mysql""github.com/jinzhu/gorm" )引入?yún)^(qū),導(dǎo)入了本次練習(xí)使用到的庫(kù)。
type User struct {gorm.ModelName string `gorm:"type:varchar(20);not null"`Telephone string `gorm:"varchar(11);not null"`Password string `gorm:"size:255"` }全局變量區(qū),定義了用戶的數(shù)據(jù)結(jié)構(gòu),主要是姓名,電話號(hào)碼和密碼。
func main() {//gin.SetMode(gin.ReleaseMode)db := InitDB()defer db.Close()db.AutoMigrate(&User{})r := gin.Default()r.POST("/api/auth/registers", func(ctx *gin.Context) {//獲取參數(shù)name := ctx.PostForm("name")telephone := ctx.PostForm("telephone")password := ctx.PostForm("password")//數(shù)據(jù)驗(yàn)證if len(telephone) != 11 {ctx.JSON(http.StatusUnprocessableEntity,gin.H{"code": 422, "msg": "手機(jī)號(hào)必須為11位"})return}if len(password) < 6 {ctx.JSON(http.StatusUnprocessableEntity,gin.H{"code": 422, "msg": "密碼必須大于6位"})return}//if len(name) == 0 {name = RandomString(10)}log.Println(name, telephone, password)//判斷手機(jī)號(hào)是否存在if IsTelephoneExist(db, telephone) {ctx.JSON(http.StatusUnprocessableEntity,gin.H{"code": 422, "msg": "該用戶已經(jīng)注冊(cè)"})return}//創(chuàng)建用戶newUser := User{Name: name,Telephone: telephone,Password: password,}db.Create(&newUser)//返回結(jié)果ctx.JSON(200, gin.H{"message": "注冊(cè)成功",})return})panic(r.Run())fmt.Println("Hello World!") }主函數(shù)區(qū),整體運(yùn)行邏輯
func IsTelephoneExist(db *gorm.DB, telephone string) bool {var user Userdb.Where("telephone=?", telephone).First(&user)if user.ID != 0 {return true}return false }子函數(shù),判斷電話號(hào)碼是否已經(jīng)注冊(cè)
func RandomString(n int) string {var letters = []byte("qwertyuiopasdfghjklxzvbnmQQERTYUOIOPASDFGHJKLZXCVBNM")result := make([]byte, n)rand.Seed(time.Now().Unix())for i := range result {result[i] = letters[rand.Intn(len(letters))]}return string(result) }子函數(shù),如果用戶沒(méi)有輸入姓名,可以生成隨機(jī)字符。
func InitDB() *gorm.DB {driverName := "mysql"host := "localhost"port := "3306"database := "test"username := "root"password := ""charset := "utf8"args := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=true",username,password,host,port,database,charset)db, err := gorm.Open(driverName, args)if err != nil {panic("failed to connect database!,err:" + err.Error())}return db }子函數(shù),初始化數(shù)據(jù)庫(kù),我的mysql沒(méi)設(shè)置密碼,所以密碼為空。
效果演示
友情支持
有問(wèn)題的可以關(guān)注公眾號(hào),博主會(huì)在24小時(shí)內(nèi)回復(fù)。
總結(jié)
以上是生活随笔為你收集整理的Go 语言框架 Gin 练习1的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: http 直接显示目录下文件_Linux
- 下一篇: html xsl xml文件,用XSL显