本文整理汇总了Golang中github.com/pressly/chi.HandlerFunc函数的典型用法代码示例。如果您正苦于以下问题:Golang HandlerFunc函数的具体用法?Golang HandlerFunc怎么用?Golang HandlerFunc使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了HandlerFunc函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: paginate
func paginate(next chi.Handler) chi.Handler {
return chi.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
// just a stub.. some ideas are to look at URL query params for something like
// the page number, or the limit, and send a query cursor down the chain
next.ServeHTTPC(ctx, w, r)
})
}
示例2: CloseNotify
// CloseNotify is a middleware that cancels ctx when the underlying
// connection has gone away. It can be used to cancel long operations
// on the server when the client disconnects before the response is ready.
func CloseNotify(next chi.Handler) chi.Handler {
fn := func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
cn, ok := w.(http.CloseNotifier)
if !ok {
panic("middleware.CloseNotify expects http.ResponseWriter to implement http.CloseNotifier interface")
}
ctx, cancel := context.WithCancel(ctx)
defer cancel()
go func() {
select {
case <-ctx.Done():
return
case <-cn.CloseNotify():
w.WriteHeader(StatusClientClosedRequest)
cancel()
return
}
}()
next.ServeHTTPC(ctx, w, r)
}
return chi.HandlerFunc(fn)
}
示例3: accountCtx
func accountCtx(h chi.Handler) chi.Handler {
handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
ctx = context.WithValue(ctx, "account", "account 123")
h.ServeHTTPC(ctx, w, r)
}
return chi.HandlerFunc(handler)
}
示例4: sup2
func sup2(next chi.Handler) chi.Handler {
hfn := func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
ctx = context.WithValue(ctx, "sup2", "sup2")
next.ServeHTTPC(ctx, w, r)
}
return chi.HandlerFunc(hfn)
}
示例5: RequestID
// RequestID is a middleware that injects a request ID into the context of each
// request. A request ID is a string of the form "host.example.com/random-0001",
// where "random" is a base62 random string that uniquely identifies this go
// process, and where the last number is an atomically incremented request
// counter.
func RequestID(next chi.Handler) chi.Handler {
fn := func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
myid := atomic.AddUint64(&reqid, 1)
ctx = context.WithValue(ctx, RequestIDKey, fmt.Sprintf("%s-%06d", prefix, myid))
next.ServeHTTPC(ctx, w, r)
}
return chi.HandlerFunc(fn)
}
示例6: ParentContext
// Set the parent context in the middleware chain to something else. Useful
// in the instance of having a global server context to signal all requests.
func ParentContext(parent context.Context) func(next chi.Handler) chi.Handler {
return func(next chi.Handler) chi.Handler {
fn := func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
pctx := context.WithValue(parent, chi.URLParamsCtxKey, chi.URLParams(ctx))
next.ServeHTTPC(pctx, w, r)
}
return chi.HandlerFunc(fn)
}
}
示例7: GetLongID
func GetLongID(next chi.Handler) chi.Handler {
fn := func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
ctx = context.WithValue(ctx, "id", strings.TrimPrefix(r.RequestURI, "/jobs/"))
next.ServeHTTPC(ctx, w, r)
}
return chi.HandlerFunc(fn)
}
示例8: Handle
func (ja *JwtAuth) Handle(paramAliases ...string) func(chi.Handler) chi.Handler {
return func(next chi.Handler) chi.Handler {
hfn := func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
var tokenStr string
var err error
// Get token from query params
tokenStr = r.URL.Query().Get("jwt")
// Get token from other query param aliases
if tokenStr == "" && paramAliases != nil && len(paramAliases) > 0 {
for _, p := range paramAliases {
tokenStr = r.URL.Query().Get(p)
if tokenStr != "" {
break
}
}
}
// Get token from authorization header
if tokenStr == "" {
bearer := r.Header.Get("Authorization")
if len(bearer) > 7 && strings.ToUpper(bearer[0:6]) == "BEARER" {
tokenStr = bearer[7:]
}
}
// Get token from cookie
if tokenStr == "" {
cookie, err := r.Cookie("jwt")
if err == nil {
tokenStr = cookie.Value
}
}
// Token is required, cya
if tokenStr == "" {
err = errUnauthorized
}
// Verify the token
token, err := ja.Decode(tokenStr)
if err != nil || !token.Valid || token.Method != ja.signer {
utils.Respond(w, 401, errUnauthorized)
return
}
ctx = context.WithValue(ctx, "jwt", token.Raw)
ctx = context.WithValue(ctx, "jwt.token", token)
next.ServeHTTPC(ctx, w, r)
}
return chi.HandlerFunc(hfn)
}
}
示例9: AdminOnly
func AdminOnly(next chi.Handler) chi.Handler {
return chi.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
isAdmin, ok := ctx.Value("acl.admin").(bool)
if !ok || !isAdmin {
http.Error(w, http.StatusText(403), 403)
return
}
next.ServeHTTPC(ctx, w, r)
})
}
示例10: AirbrakeRecoverer
// Airbrake recoverer middleware to capture and report any panics to
// airbrake.io.
func AirbrakeRecoverer(apiKey string) func(chi.Handler) chi.Handler {
airbrake.ApiKey = apiKey
return func(next chi.Handler) chi.Handler {
return chi.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
if apiKey != "" {
defer airbrake.CapturePanic(r)
}
next.ServeHTTPC(ctx, w, r)
})
}
}
示例11: ArticleCtx
func ArticleCtx(next chi.Handler) chi.Handler {
return chi.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
articleID := chi.URLParams(ctx)["articleID"]
article, err := dbGetArticle(articleID)
if err != nil {
http.Error(w, http.StatusText(404), 404)
return
}
ctx = context.WithValue(ctx, "article", article)
next.ServeHTTPC(ctx, w, r)
})
}
示例12: AccessControl
// AccessControl is an example that just prints the ACL route + operation that
// is being checked without actually doing any checking
func AccessControl(next chi.Handler) chi.Handler {
hn := func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
route, ok := ctx.Value("acl.route").([]string)
if !ok {
http.Error(w, "undefined acl route", 403)
return
}
// Put ACL code here
log.Printf("Checking permission to %s %s", r.Method, strings.Join(route, " -> "))
next.ServeHTTPC(ctx, w, r)
}
return chi.HandlerFunc(hn)
}
示例13: Timeout
// Timeout is a middleware that cancels ctx after a given timeout.
func Timeout(timeout time.Duration) func(next chi.Handler) chi.Handler {
return func(next chi.Handler) chi.Handler {
fn := func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer func() {
cancel()
if ctx.Err() == context.DeadlineExceeded {
w.WriteHeader(StatusServerTimeout)
}
}()
next.ServeHTTPC(ctx, w, r)
}
return chi.HandlerFunc(fn)
}
}
示例14: Recoverer
// Recoverer is a middleware that recovers from panics, logs the panic (and a
// backtrace), and returns a HTTP 500 (Internal Server Error) status if
// possible.
//
// Recoverer prints a request ID if one is provided.
func Recoverer(next chi.Handler) chi.Handler {
fn := func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
reqID := GetReqID(ctx)
printPanic(reqID, err)
debug.PrintStack()
http.Error(w, http.StatusText(500), 500)
}
}()
next.ServeHTTPC(ctx, w, r)
}
return chi.HandlerFunc(fn)
}
示例15: Logger
// Logger is a middleware that logs the start and end of each request, along
// with some useful data about what was requested, what the response status was,
// and how long it took to return. When standard output is a TTY, Logger will
// print in color, otherwise it will print in black and white.
//
// Logger prints a request ID if one is provided.
func Logger(next chi.Handler) chi.Handler {
fn := func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
reqID := GetReqID(ctx)
prefix := requestPrefix(reqID, r)
lw := wrapWriter(w)
t1 := time.Now()
defer func() {
t2 := time.Now()
printRequest(prefix, reqID, lw, t2.Sub(t1))
}()
next.ServeHTTPC(ctx, lw, r)
}
return chi.HandlerFunc(fn)
}