我已經Go使用該Gin框架構建了一個 API 。我在 API 中有一條路線可以讓用戶使用id. 但現在我也想通過用戶名來獲取用戶。所以我嘗試了與讓用戶使用id. 但它在編譯程序中給了我一個錯誤。你們能告訴我我該怎么做嗎?
謝謝你。
路線 -
grp.GET("/users", controllers.GetUsers)
grp.GET("/users/:id", controllers.GetUser)
grp.GET("/users/:username", controllers.GetUserByUsername) //error - panic: ':username' in new path '/users/:username' conflicts with existing wildcard ':id' in existing prefix '/users/:id'
grp.POST("/users", controllers.CreateUser)
grp.PATCH("/users/:id", controllers.UpdateUser)
grp.DELETE("/users/:id", controllers.DeleteUser)
控制器 -
func GetUser(c *gin.Context) {
paramID := c.Params.ByName("id")
ctx := context.Background()
sa := option.WithCredentialsFile(firestoreFilePath)
app, err := firebase.NewApp(ctx, nil, sa)
if err != nil {
log.Fatalln(err)
}
client, err := app.Firestore(ctx)
if err != nil {
log.Fatalln(err)
}
defer client.Close()
dsnap, err := client.Collection("users").Doc(paramID).Get(ctx)
if err != nil {
fmt.Print(err)
c.IndentedJSON(http.StatusNotFound, gin.H{
"message": "User not found",
})
return
}
m := dsnap.Data()
c.IndentedJSON(http.StatusNotFound, gin.H{
"User": m,
"message": "User returned successfully",
})
}
API 回應 -
[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "[email protected]",
},
{
"id": 2,
"name": "Ervin Howell",
"username": "Antonette",
"email": "[email protected]",
},
{
"id": 3,
"name": "Clementine Bauch",
"username": "Samantha",
"email": "[email protected]",
}
]
uj5u.com熱心網友回復:
您不能使用相同的方法、相同的路徑前綴和相同位置的路徑引數宣告路由。不幸的是,在路由匹配期間不會檢查路由后綴。
你必須給它一個不同的名字。由于路由可能映射到一個“用戶”資源,您可以這樣呼叫它,并保持它的 RESTful:
// instead of /users
grp.GET("/user/:username", controllers.GetUserByUsername)
然而,用戶 id 也可能是唯一的,因此呼叫其他 route 也同樣有意義/user/:id。因此,您可以保留/users前綴并在前綴和引數之間提供不同的固定路徑段:
// prefix is /users/id
grp.GET("/users/id/:id", controllers.GetUser)
// prefix is /users/username
grp.GET("/users/username/:username", controllers.GetUserByUsername)
或者您可以使用一個路由和查詢來做到這一點,并在中間處理程式中檢查查詢引數。這樣做的優點是可以通過一條路線支持任意數量的搜索引數:
// invoked as /users/find?p=xxx&t=yyy
// p stands for 'parameter'
// t stands for 'type'
grp.GET("/users/find", func(c *gin.Context) {
switch c.Query("t") {
case "id":
// inspect p in this handler knowing it's an id
controllers.GetUser(c)
case "username":
// inspect p in this handler knowing it's a username
controllers.GetUserByUsername(c)
default:
c.AbortWithStatus(http.StatusBadRequest)
}
})
uj5u.com熱心網友回復:
這是 gin 中的一個已知限制。您必須使所有路徑都是唯一的。就像添加前綴如下:
grp.GET("/users/username/:username", controllers.GetUserByUsername)
有關此問題執行緒的更多資訊:https : //github.com/gin-gonic/gin/issues/1301
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/392436.html
