这是我参与「第五届青训营 」笔记创作活动的第10天
前置学习
Gorm 中文文档:gorm.io/zh_CN/docs/…
下载simple-demo: github.com/RaymondCode…
接口文档:www.apifox.cn/apidoc/shar…
查看接口文档,获取接口信息
返回格式如下:
{
"status_code": 0,
"status_msg": "string",
"user": {
"id": 0,
"name": "string",
"follow_count": 0,
"follower_count": 0,
"is_follow": true
}
}
查看源码user.go,发现demo是用硬编码保存了用户的信息,首先应该改成数据库来存储用户的信息。
var usersLoginInfo = map[string]User{
"zhangleidouyin": {
Id: 1,
Name: "zhanglei",
FollowCount: 10,
FollowerCount: 5,
IsFollow: true,
},
}
这里采用sqlite和gorm来进行crud,将用户的信息转换为结构体存储,加上gorm.Model
type User struct {
gorm.Model
Id int64
Name string
FollowCount int64
FollowerCount int64
IsFollow bool
}
然后创建初始化函数,以下是db.go的全部文件,将其加入main包中
package main
import (
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
type User struct {
gorm.Model
Id int64
Name string
FollowCount int64
FollowerCount int64
IsFollow bool
}
var db *gorm.DB
func initUserDB() {
var err error
db, err = gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
db.AutoMigrate(&User{})
}
然后就可以通过db进行查询,一些gorm的基本操作如下:
GORM is a popular ORM library for the Go programming language. To connect to a database with GORM, you'll first need to import the appropriate database driver for the database you're using (e.g. import _ "github.com/go-sql-driver/mysql" for MySQL).
Next, you'll need to open a database connection using the DB function from the GORM library, passing in the driver name, database name, and any other necessary credentials as arguments. Here's an example for connecting to a MySQL database:
goCopy code
db, err := gorm.Open("mysql", "user:password@/dbname?charset=utf8&parseTime=True&loc=Local")
if err != nil {
panic("failed to connect database")
}
defer db.Close()
To create a table with GORM, you'll first need to define a struct that represents the table. The struct fields will correspond to columns in the table, and GORM will automatically create a table with the same name as the struct (unless you specify a different name using the table tag). Here's an example struct definition:
goCopy code
type User struct {
gorm.Model
Name string
Age int
}
To create the table, call the AutoMigrate method on your db object, passing in the struct as an argument:
lessCopy code
db.AutoMigrate(&User{})
This will create a users table in the database with columns for id, created_at, updated_at, deleted_at, name, and age.
Here's an example using Find to find all User records in the table:
bashCopy code
var users []User
db.Find(&users)
Here's an example using Where to find User records with a specific condition:
bashCopy code
var users []User
db.Where("name = ?", "John").Find(&users)
In the Where example, the ? placeholder is used to prevent SQL injection attacks, and the second argument to Where provides the values to replace the placeholders.
These methods will populate the users variable with the matching records from the database. You can then access the properties of the records using the dot notation, like this:
bashCopy code
fmt.Println(users[0].Name)
接下来是改写函数,原来的函数逻辑为
if user, exist := usersLoginInfo[token]; exist {
c.JSON(http.StatusOK, UserResponse{
Response: Response{StatusCode: 0},
User: user,
})
} else {
c.JSON(http.StatusOK, UserResponse{
Response: Response{StatusCode: 1, StatusMsg: "User doesn't exist"},
})
}
由于token还没有实现,本文只实现查询user_id的操作,token鉴权应该用JWT实现
可以使用chatgpt帮我们写gorm语句
Input:
有如下结构体
type User struct {
gorm.Model
Id int64
Name string
FollowCount int64
FollowerCount int64
IsFollow bool
}
在数据库db中查询user的Id为user_id的用户,结果保存在var user User中
也可以用chatgpt生成测试数据,采用sql lite shell工具或者可视化工具访问数据库即可。