Go Web Programming (I) – Golang uses Gin Gorm to write Restful apis
The basic restful API service is completed in the previous chapter. Based on the previous chapter, this article adds:
-
Custom table names
-
Accepts a JSON parameter
-
Custom return type
-
PostgreSQL JSONB type field parsing
1. Customize the table name
The default GORM uses the plural of entity(model), for example: Student corresponds to students
1.1 Specifying the table name
Implement the TableName interface in entity and return a custom TableName
Func (Student) TableName() string {return "t_student"}Copy the code
1.2 Specifying the table name prefix
db, err := gorm.Open("postgres", "Host =127.0.0.1 port=5432 user=postgres dbname=test password=root sslmode=disable") // Add the table name prefix gorm.DefaultTableNameHandler = func (db *gorm.DB, defaultTableName string) string { return "prefix_" + defaultTableName }Copy the code
2. Receive JSON parameters
The data inserted before is generated in the code, now change to generate from the front end of the parameter, modify the previous code:
// Insert data api.POST("/add", func(context *gin.Context) {/*student := entity. student {Name: "blind ", Age: 26} dao.AddStudent(&student) context.JSON(http.StatusOK, gin.H{ "msg": Student := entity.student {} context.BindJSON(&student) FMT.Println(" " ") fmt.Println(student) dao.AddStudent(&student) context.JSON(http.StatusOK, gin.H{ "data": student, }) })Copy the code
3. Custom return body
In daily development, a common return body structure is defined to facilitate collaborative development. The following is a custom return body to be used in GIN:
3.1 Return the body definition
type ResponseResult struct { Code int `json:"code"` Msg string `json:"msg"` Data interface{} `json:"data"` } // Success /** ResponseResult{return &responseresult {http.statusok, "Success ", Func Fail(code int, MSG string) *ResponseResult {return &ResponseResult{http.statusok, MSG, nil} }Copy the code
3.2 the use of
Take the code inserted above
// Insert data api.POST("/add", func(context *gin.Context) {/*student := entity. student {Name: "blind ", Age: 26} dao.AddStudent(&student) context.JSON(http.StatusOK, gin.H{ "msg": Student := entity.student {} context.BindJSON(&student) FMT.Println(" " ") fmt.Println(student) dao.AddStudent(&student) /*context.JSON(http.StatusOK, gin.H{ "msg": JSON(http.statusok, common.success (student))})Copy the code
4. PostgreSQL JSONB field parsing
4.1 Defining the JSONB type
Add in 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) }Copy the code
#### 4.2 Adding the JSONB attribute
Add the Result attribute to student.go
Result JSONB `gorm:"type:jsonb" json:"result"`
Copy the code