0.Preface
The development environment used in this series is as follows:
- goland
- go 1.17.1
In this section, we first completed the import of the gin framework in the project and wrote helleworld for testing. Then we imported the gorm package and combined gorm and gin to develop a simple registration logic.
1. Create a working directory
Create the gin_test project in goland and create the main.go file
2. Install and test the GIN framework
2.1 Install gin package
Enter the gin_test directory created in the previous section and enter the following command
go get -u github.com/gin-gonic/gin
Note that you may encounter a timeout error here because the package is blocked. We can configure the GO environment to solve this problem. For details, see the blogger's other article go module configuration .
After installation, we can see many gin dependencies in go.mod.
2.2 Write helloworld for testing
Enter the following code in the main.go file:
package main
import "github.com/gin-gonic/gin"
func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
r.Run() // listen and serve on 0.0.0.0:8080
}
After running, enter http://localhost:8080/ping to see the pong message.
3. Install and test the gorm package
Run the following command in the gin_test directory:
go get -u gorm.io/gorm
Here we are using mysql, so we also need to include the following packages:
go get gorm.io/driver/mysql
We wrote the following simple code for testing. The code defines a user structure, which will be mapped to a table in the database, and some addition, deletion, modification and query operations are performed based on this table:
package main
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
//定义结构体到数据库的映射,设置name为非空且唯一
type User struct {
gorm.Model
Name string `gorm:"not null;unique"`
Telephone string
Password string
}
func main() {
db:=InitDb()
//自动创建数据表
db.AutoMigrate(&User{})
db.Create(&User{Name: "yzy",
Password: "123456"})
var user User
fmt.Print(user)
fmt.Printf("----------\n")
db.First(&user,"name=?","yzy")
fmt.Print(user)
fmt.Printf("----------\n")
}
func InitDb() *gorm.DB{
//一些数据库的参数
username:="root"
password:="123456"
host:="localhost"
port:="3306"
charset:="utf8"
database:="test" //使用test数据库
dns:=fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=true",
username,
password,
host,
port,
database,
charset)
//后面还可以传入一些对数据库特殊的定义
db,err:=gorm.Open(mysql.Open(dns))
if err != nil {
panic("failed to connect database,err:"+err.Error())
}
return db
}
Don't forget to start the database service and create the database specified in the code before running.
net start mysql
//进入mysql
mysql -u root -p
//创建数据库
creat database test
Query the database after running
select * from users;
4. Write registration logic
code show as below:
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type User struct {
gorm.Model
Name string
Telephone string `gorm:"unique;not null"`
Password string `gorm:"not null"`
}
func main(){
db:=InitDb()
db.AutoMigrate(&User{})
router:=gin.Default()
router.GET("/register",Register)
router.Run()
}
func Register(c *gin.Context){
db:=InitDb()
//获取数据
name:=c.Query("name")
password:=c.Query("password")
telephone:=c.Query("telephone")
if len(telephone)!=11{
c.JSON(400,gin.H{
"error":"the telephone is not correct",
})
return
}
//判断
if isTelephoneExist(db,telephone){
c.JSON(400,gin.H{
"error":"the telephone is already exit",
})
return
}
//插入数据
db.Create(&User{Name: name,Password: password,Telephone: telephone})
c.JSON(200,gin.H{
"msg":"succeed",
})
return
}
func isTelephoneExist(db *gorm.DB,telephone string)bool{
var user User
db.Where("password=?",telephone).First(&user)
if user.ID!=0{
return true
}else{
return false
}
}
func InitDb()*gorm.DB{
username:="root"
password:="123456"
database:="gin_demo"
charset:="utf8"
port:="3306"
host:="localhost"
dns:=fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=True",
username,
password,
host,
port,
database,
charset)
db,err:=gorm.Open(mysql.Open(dns))
if err != nil {
panic("can't connect to the mysql"+err.Error())
}
return db
}
6. Summary
All the functions of a small demo implemented today are written in one package. After the business expands, such an architecture will become very bloated and difficult to maintain, because the project architecture will be redesigned next.