Go Web 编程(一)- Golang 使用 gin gorm 编写Restful API
上一章节完成基本的restful API 服务,本文在上一章节的基础上增加:
-
自定义表名
-
接收JSON类型的参数
-
自定义的返回类型
-
PostgreSQL JSONB类型字段的解析
1. 自定义表名
默认的GORM使用entity(model)的复数表明,例如:student对应的表名就是students
1.1 指定表名
在entity中实现 TableName接口,返回自定义的表名即可
func (Student) TableName() string {
// 自定义表名
return "t_student"
}
1.2 指定表名前缀
db, err := gorm.Open("postgres", "host=127.0.0.1 port=5432 user=postgres dbname=test password=root sslmode=disable")
// 添加表名前缀
gorm.DefaultTableNameHandler = func (db *gorm.DB, defaultTableName string) string {
return "prefix_" + defaultTableName
}
2. 接收JSON类型的参数
之前插入的数据是代码中生成,现在改成从前端传参生成,对之前的代码进行改造:
// 插入数据
api.POST("/add", func(context *gin.Context) {
/*student := entity.Student{Name: "阿盲", Age: 26}
dao.AddStudent(&student)
context.JSON(http.StatusOK, gin.H{
"msg": "success",
})*/
// 接收前端传入的参数
student := entity.Student{}
context.BindJSON(&student)
fmt.Println("接收到的参数为:")
fmt.Println(student)
dao.AddStudent(&student)
context.JSON(http.StatusOK, gin.H{
"data": student,
})
})
3. 自定义的返回体
日常的开发过程中,都会定义一个通用的返回体结构,便于协同开发,下面自定义一个返回体,并在gin中应用:
3.1 返回体定义
type ResponseResult struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data interface{} `json:"data"`
}
// Success /**成功返回结构
func Success(data interface{}) *ResponseResult {
return &ResponseResult{http.StatusOK, "success", data}
}
// Fail /**失败返回的结构
func Fail(code int, msg string) *ResponseResult {
return &ResponseResult{http.StatusOK, msg, nil}
}
3.2 使用
以上面插入的代码为例
// 插入数据
api.POST("/add", func(context *gin.Context) {
/*student := entity.Student{Name: "阿盲", Age: 26}
dao.AddStudent(&student)
context.JSON(http.StatusOK, gin.H{
"msg": "success",
})*/
// 接收前端传入的参数
student := entity.Student{}
context.BindJSON(&student)
fmt.Println("接收到的参数为:")
fmt.Println(student)
dao.AddStudent(&student)
/*context.JSON(http.StatusOK, gin.H{
"msg": student,
})*/
// 自定义的返回体
context.JSON(http.StatusOK, common.Success(student))
})
4. PostgreSQL JSONB类型字段的解析
4.1 定义JSONB类型
在sutdent.go中添加
type JSONB []interface{}
// Value Marshal
func (a JSONB) Value() (driver.Value, error) {
return json.Marshal(a)
}
// Scan Unmarshal
func (a *JSONB) Scan(value interface{}) error {
b, ok := value.([]byte)
if !ok {
return errors.New("type assertion to []byte failed")
}
return json.Unmarshal(b, &a)
}
#### 4.2 添加JSONB属性
student.go中添加Result属性
Result JSONB `gorm:"type:jsonb" json:"result"`