本文整理匯總了Golang中github.com/rs/xhandler.Chain.Add方法的典型用法代碼示例。如果您正苦於以下問題:Golang Chain.Add方法的具體用法?Golang Chain.Add怎麽用?Golang Chain.Add使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類github.com/rs/xhandler.Chain
的用法示例。
在下文中一共展示了Chain.Add方法的1個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: ExampleAddChain
func ExampleAddChain() {
c := xhandler.Chain{}
close := xhandler.CloseHandler
cors := cors.Default().Handler
timeout := xhandler.TimeoutHandler(2 * time.Second)
auth := func(next xhandler.HandlerC) xhandler.HandlerC {
return xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
if v := ctx.Value("Authorization"); v == nil {
http.Error(w, "Not authorized", http.StatusUnauthorized)
return
}
next.ServeHTTPC(ctx, w, r)
})
}
c.Add(close, cors, timeout)
mux := http.NewServeMux()
// Use c.Handler to terminate the chain with your final handler
mux.Handle("/", c.Handler(xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "Welcome to the home page!")
})))
// Create a new chain from an existing one, and add route-specific middleware to it
protected := c.With(auth)
mux.Handle("/admin", protected.Handler(xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "protected endpoint!")
})))
}