我已經在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]", }]
1 回答

MMTTMM
TA貢獻1869條經驗 獲得超4個贊
這是杜松子酒的一個已知限制。您必須使所有路徑都獨一無二。就像添加如下前綴一樣:
grp.GET("/users/username/:username", controllers.GetUserByUsername)
有關此問題線程的更多信息: https ://github.com/gin-gonic/gin/issues/1301
- 1 回答
- 0 關注
- 115 瀏覽
添加回答
舉報
0/150
提交
取消