Go 语言框架 Gin 练习2
生活随笔
收集整理的這篇文章主要介紹了
Go 语言框架 Gin 练习2
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
目錄
文章目錄
- 目錄
- 1 介紹
- 2 練習
- 友情援助
1 介紹
Gin是一個golang的微框架,封裝比較優雅,API友好,源碼注釋比較明確,具有快速靈活,容錯方便等特點
對于golang而言,web框架的依賴要遠比Python,Java之類的要小。自身的net/http足夠簡單,性能也非常不錯
借助框架開發,不僅可以省去很多常用的封裝帶來的時間,也有助于團隊的編碼風格和形成規范.
2 練習
本次練習主要在上一次代碼的基礎上進行了進一步的優化,
對源代碼進行了層次分離。
整體目錄結構如圖:
## 2.1 主代碼
主函數,主要調用了一個GIn的默認web服務器實例,
并將其運行,開始監聽。
common 包的database文件,主要實現了,初始化一個數據庫和獲得一個數據實例等操作。
package Controllerimport ("GINVUE/Model""GINVUE/common""GINVUE/util""log""net/http""github.com/gin-gonic/gin""github.com/jinzhu/gorm" )func Register(ctx *gin.Context) {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 || len(password) > 11 {ctx.JSON(http.StatusUnprocessableEntity,gin.H{"code": 422, "msg": "密碼必須大于6位且小于11位"})return}//if len(name) == 0 {name = util.RandomString(10)}log.Println(name, telephone, password)//判斷手機號是否存在if util.IsTelephoneExist(db, 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(200, gin.H{"message": "注冊成功",})return }Controller 包,主要實現路由管理,目前只有一個注冊路由處理函數,
后續還會有登陸等等。
Model 包主要定義了數據庫存儲對象原型。
package utilimport ("math/rand""time" )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) } func IsTelephoneExist(db *gorm.DB, telephone string) bool {var user Model.Userdb.Where("telephone=?", telephone).First(&user)if user.ID != 0 {return true}return false }util 包主要提供了一些通用的功能代碼。
package mainimport ("GINVUE/Controller""github.com/gin-gonic/gin" ) func CollectRouter(r *gin.Engine) *gin.Engine {r.POST("/api/auth/register", Controller.Register)r.POST("/api/auth/login", Controller.Login)return r }main包的第二個函數,負責管理路由。
友情援助
有問題的可以關注公眾號,博主會在24小時內回復。
總結
以上是生活随笔為你收集整理的Go 语言框架 Gin 练习2的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: html xsl xml文件,用XSL显
- 下一篇: java时间中间加横杠方法_知识点:ja