介绍

restful用来描述某一个或某几个对象主体的crud操作的url路径,本文将举出示例.

源码

type User struct{
Id int `json:"id"`
Username string `json:"username"`
}
var users = []User{User{1, "Zhang San"}, User{2, "Li Si"}, User{3, "Wang Wu"}}
func main(){
r := gin.Default()
r.GET("/user/", ListUsers)
r.GET("/user/:id/", GetUser)
r.POST("/user/", AddUser)
r.PATCH("/user/:id/", UpdateUser)
r.DELETE("/user/:id/", DeleteUser)
r.Run(":8080")
}
func ListUser(c *gin.Context){
c.JSON(200, gin.H{"message":"success", "count":len(users), "data": users})
}
func GetUser(c *gin.Context){
id := c.Param("id")
for _,user:=range users{
if id == strconv.ItoA(user.Id) {
c.JSON(200, gin.H{"message":"success", "data": user})
return
}
}
c.JSON(400, gin.H{"message":fmt.Sprintf("id '%s' user not found", id)})
}
func AddUser(c *gin.Context){
var user User
c.Bind(&user)
users = append(users, user)
c.JSON(200, gin.H{"message":"success"})
}
func UpdateUser(c *gin.Context){
id := c.Param("id")
var user User
c.Bind(&user)
for i,user:=range users{
if id == strconv.ItoA(user.Id) {
users[i].Username = user.Username
c.JSON(200, gin.H{"message":"success", "data": users})
return
}
}
c.JSON(400, gin.H{"message": fmt.Sprintf("id '%s' user not found", id)})
}
func DeleteUser(c *gin.Context){
id := c.Param("id")
for i,user:=range users{
if id == strconv.ItoA(user.Id) {
users = append(users[:i], users[i+1:])
c.JSON(200, gin.H{"message":"success", "data": users})
return
}
}
c.JSON(400, gin.H{"message": fmt.Sprintf("id '%s' user not found", id)})
}

多个对象请求时:

r.POST("/user/teacher/record/", nil)

对象名称过长时

r.POST("/user-password/", nil)

总结

  1. 路由结尾闭环​​/user/​​​ ,而不是 ​​/user​
  2. 无纯动词​​/user/click-record/​​​, 而不是​​/user/click/record/​
  3. 无驼峰无下划线​​/user/game/info/​​​,而不是​​/user_game_info/​​​或​​/userGameInfo/​

以上为我的restful标准,存在异议的可提,不纳。