Golang.org 有一篇關(guān)于如何做到這一點(diǎn)的博文:http : //blog.golang.org/error-handling-and-go他們基本上制作了一種新類型type appHandler func(http.ResponseWriter, *http.Request) error它像這樣實(shí)現(xiàn)了 http.Handler 接口func (fn appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { if err := fn(w, r); err != nil { http.Error(w, err.Error(), 500) }}有了這個(gè),你就可以在你的 handleFunc 上返回錯(cuò)誤,這很棒。但我使用的是 julienschmidt httprouter,它使用一個(gè)函數(shù)而不是一個(gè)實(shí)現(xiàn) http.Handler 的接口。我喜歡使用這個(gè)路由器,因?yàn)樗С置麉?shù)。如何在 httprouter.Handler 函數(shù)周圍包裝“東西”,以便我可以返回錯(cuò)誤并返回其他東西?有沒(méi)有辦法做到這一點(diǎn),以防止重復(fù)的錯(cuò)誤處理?我找不到辦法。
1 回答

慕哥6287543
TA貢獻(xiàn)1831條經(jīng)驗(yàn) 獲得超10個(gè)贊
使用閉包:
type Handle func(http.ResponseWriter, *http.Request, Params)
type ErrHandle func(http.ResponseWriter, *http.Request, Params) error
func (eh ErrHandle) ToHandle() Handle {
return func(w http.ResponseWriter, r *http.Request, p Params) {
if err := eh(w, r, p); err != nil {
http.Error(w, err.Error(), 500)
}
}
}
- 1 回答
- 0 關(guān)注
- 211 瀏覽
添加回答
舉報(bào)
0/150
提交
取消