1 回答

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