1 回答

TA貢獻1876條經驗 獲得超7個贊
就像你說的,命名參數匹配整個路徑段。您可以通過檢查單個處理程序中的后綴并從那里分支來解決此問題。
router.GET("/v1/:id", Content)
func Content(w http.ResponseWriter, r *http.Request) {
params := httprouter.ParamsFromContext(r.Context())
if strings.HasSuffix(params.ByName("id"), ".json") {
ContentJson()
} else {
ContentDefault()
}
}
在沒有多個處理程序的情況下處理不同響應類型的另一種方法是使用Accept標頭。
router.GET("/v1/:id", Content)
func Content(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Accept") == "application/json" {
ContentJson()
} else {
ContentDefault()
}
}
然后,您將在請求中設置標頭。這可能是最干凈的解決方案,但對所有用戶來說并不那么簡單。
curl -H "Accept: application/json" 'http://my.api/v1/:id`
- 1 回答
- 0 關注
- 111 瀏覽
添加回答
舉報