1、項目開發准備
Go版本:1.16.2 開發工具:GoLand 使用框架:Gin ORM框架:GORM 數據庫:MySQL
2、項目結構
3、項目環境准備:Gin和GORM
1、開啟GO111MODULE並修改Go代理(用下面兩個命令把下圖中標出的兩個地方修改成跟我一樣的配置)
go env -w GO111MODULE=on
go env -w GOPROXY=https://goproxy.cn,direct(修改這個是因為原有的谷歌代理在國內不行)
2、安裝Gin(在GoLand工具命令行下執行以下命令)
go get -u github.com/gin-gonic/gin
go get -u gorm.io/gorm
【注意:這一步執行完后,它會自動在go.mod文件中引入響應的依賴】
3、安裝Gorm
4、安裝mysql數據庫驅動
go get -u gorm.io/driver/mysql
4、項目源碼
//go.mod文件源碼 module Gin_demo go 1.16 //通過命令【go get -u github.com/gin-gonic/gin】安裝gin框架 //引入gin框架后,會自動在這里引入依賴 require ( github.com/gin-gonic/gin v1.7.2 // indirect github.com/go-playground/validator/v10 v10.6.1 // indirect github.com/golang/protobuf v1.5.2 // indirect github.com/json-iterator/go v1.1.11 // indirect github.com/leodido/go-urn v1.2.1 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd github.com/modern-go/reflect2 v1.0.1 // indirect github.com/ugorji/go v1.2.6 // indirect golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a // indirect golang.org/x/sys v0.0.0-20210521203332-0cec03c779c1 // indirect golang.org/x/text v0.3.6 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect gorm.io/driver/mysql v1.1.0 // indirect gorm.io/gorm v1.21.10 // indirect )
main.go 文件源碼
package main import ( "fmt" "github.com/gin-gonic/gin" "gorm.io/driver/mysql" "gorm.io/gorm" "io/ioutil" "log" "math/rand" "net/http" "time" ) //此方法在該項目中未用,不用管 func sayHello(w http.ResponseWriter, r *http.Request) { b, _ := ioutil.ReadFile("./hello.txt") _, _ = fmt.Fprintln(w, string(b)) } type User struct { gorm.Model //'gorm:"type:varchar(20);not null"' Name string Phone string Password string } func main() { db := InitDB() //傳統的Web服務寫法 //http.HandleFunc("/hello", sayHello) //err := http.ListenAndServe(":9090", nil) //if err != nil { // fmt.Printf("http server faile,err:%v\n", err) // return //} //fmt.Println("項目啟動成功") //利用Gin框架的web寫法,來源於gin官網 r := gin.Default() r.POST("/api/auth/register", func(c *gin.Context) { //獲取參數 name := c.PostForm("name") phone := c.PostForm("phone") password := c.PostForm("password") //數據驗證 if len(phone) != 11 { c.JSON(http.StatusUnprocessableEntity, gin.H{"code": 422,
"msg": "手機號格式不正確"}) return } if len(password) < 6 { c.JSON(http.StatusUnprocessableEntity, gin.H{"code": 422,
"msg": "密碼不能少於6位"}) return } if len(name) == 0 { name = RandomString(10) return } log.Print(name, phone, password) //判斷手機號是否存在 if isPhoneExist(db, phone) { c.JSON(http.StatusUnprocessableEntity, gin.H{"code": 422,
"msg": "用戶已存在,不能注冊"}) return } //創建新用戶 newUser := User{ Name: name, Phone: phone, Password: password, } db.Create(&newUser) //返回結果 c.JSON(200, gin.H{ "message": "注冊成功", }) }) _ = r.Run() // listen and serve on 0.0.0.0:8080 panic(r.Run()) } func isPhoneExist(db *gorm.DB, phone string) bool { var user User db.Where("phone = ?", phone).First(&user) if user.ID != 0 { return true } return false } //隨機產生英文字符,可設定長度 func RandomString(n int) string { var letters =[]byte("asdfghjklzxcvbnmqwertyuiopASDFGHJKLZXCVBNMQWERTYUIOP") 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 {
//前提是你要先在本機用Navicat創建一個名為go_db的數據庫 host := "localhost" port := "3306" database := "go_db" username := "root" password := "123456" charset := "utf8" dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=true", username, password, host, port, database, charset)
//這里 gorm.Open()函數與之前版本的不一樣,大家注意查看官方最新gorm版本的用法 db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{}) if err != nil { panic("Error to Db connection, err: " + err.Error()) } //這個是gorm自動創建數據表的函數。它會自動在數據庫中創建一個名為users的數據表 _ = db.AutoMigrate(&User{}) return db }
5、用Postman測試接口,按照代碼中的參數傳入測試
《全文完》
有不懂的小伙伴歡迎留言交流!