這是一個建立於
的文章,其中的資訊可能已經有所發展或是發生改變。
最近寫GOLANG項目,不使用架構,路由選擇httprouter
現在想實現一個需求:在不修改httprouter源碼的前提下,對所有註冊的路由handle進行異常捕獲。
大家都知道golang使用panic()產生異常,然後可以recover()來捕獲到異常,否則主程式直接宕掉,這是我們不希望看到的。
或者全程檢查error,不主動拋出異常。即便這樣,可能異常依然不能避免。
既然要recover(),但又不想在每個handle裡面都去recover()一遍,如果你也有這樣的需求,下面講到的可能對你有用。
func RegRouters(r *httprouter.Router) { r.GET("/", Home) r.GET("/contact", Contact)}func Home(w http.ResponseWriter, r *http.Request, params httprouter.Params) { defer func() { if pr := recover(); pr != nil { fmt.Printf("panic recover: %v\r\n", pr) debug.PrintStack() } }() //something}func Contact(w http.ResponseWriter, r *http.Request, params httprouter.Params) { defer func() { if pr := recover(); pr != nil { fmt.Printf("panic recover: %v\r\n", pr) debug.PrintStack() } }() //something}
正常的路由表長這樣。在C#中相當於對每個請求加try...catch,將業務上程式碼封裝裹起來。
可能你已經想到了,對,包裹起來,像這樣:
func RegRouters(r *httprouter.Router) { r.GET("/", WrapHandle(Home)) r.GET("/contact", WrapHandle(Contact))}
那這個wrap方法長什麼樣呢?他需要有一個handle類型的參數,同時傳回值要能被httprouter接收,直接上代碼
func WrapHandle(handle httprouter.Handle) httprouter.Handle { return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) { defer func() { if pr := recover(); pr != nil { fmt.Printf("panic recover: %v\r\n", pr) debug.PrintStack() } }() handle(w, r, p) }}
是不是很簡單~ 我們再改造一下,加一個上下文,把handle簡化一下
func WrapHandle(handle func(ctx *context.Context)) httprouter.Handle { return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) { defer func() { if pr := recover(); pr != nil { fmt.Println("panic recover: %v", pr) debug.PrintStack() } }() ctx := context.NewContext(w, r, p) handle(ctx) }}func Home(ctx *context.Context) { defer func() { if pr := recover(); pr != nil { fmt.Printf("panic recover: %v\r\n", pr) debug.PrintStack() } }() //something}func Contact(ctx *context.Context) { defer func() { if pr := recover(); pr != nil { fmt.Printf("panic recover: %v\r\n", pr) debug.PrintStack() } }() //something id = ctx.FormInt64("id") //通過context從FORM取值,並轉換為int64}
看出有什麼不同了嗎?對,多了一個context包,handle的參數也減少到一個,主要是context上可以做更多的事情。
一個簡單的請求內容相關的原型:
type Context struct { responseWriter http.ResponseWriter request *http.Request params httprouter.Params Data map[string]interface{}}func NewContext(w http.ResponseWriter, r *http.Request, params httprouter.Params) *Context { ctx := new(Context) ctx.responseWriter = w ctx.request = r ctx.params = params ctx.Data = make(map[string]interface{}) return ctx}func (ctx *Context) FormValue(name string) string { return ctx.request.FormValue(name)}func (ctx *Context) FormInt64(name string) int64 { value, _ := strconv.ParseInt(ctx.FormValue(name), 10, 64) return value}//更多擴充....
好了,先到這裡,希望對你有協助。