Esempio n. 1
0
File: main.go Progetto: raj347/chi
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)
	})
}
Esempio n. 2
0
// 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)
}
Esempio n. 3
0
File: main.go Progetto: vladdy/chi
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)
}
Esempio n. 4
0
File: main.go Progetto: vladdy/chi
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)
}
Esempio n. 5
0
// 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)
}
Esempio n. 6
0
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)
}
Esempio n. 7
0
File: main.go Progetto: raj347/chi
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)
	})
}
Esempio n. 8
0
File: main.go Progetto: raj347/chi
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)
	})
}
Esempio n. 9
0
// 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)
}
Esempio n. 10
0
// 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)
}
Esempio n. 11
0
File: logger.go Progetto: raj347/chi
// 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)
}
Esempio n. 12
0
// Authenticator is a default authentication middleware to enforce access following
// the Verifier middleware. The Authenticator sends a 401 Unauthorized response for
// all unverified tokens and passes the good ones through. It's just fine until you
// decide to write something similar and customize your client response.
func Authenticator(next chi.Handler) chi.Handler {
	return chi.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		if jwtErr, ok := ctx.Value("jwt.err").(error); ok {
			if jwtErr != nil {
				http.Error(w, http.StatusText(401), 401)
				return
			}
		}

		jwtToken, ok := ctx.Value("jwt").(*jwt.Token)
		if !ok || jwtToken == nil || !jwtToken.Valid {
			http.Error(w, http.StatusText(401), 401)
			return
		}

		// Token is authenticated, pass it through
		next.ServeHTTPC(ctx, w, r)
	})
}
Esempio n. 13
0
// 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.
//
// Logger has been designed explicitly to be Good Enough for use in small
// applications and for people just getting started with Goji. It is expected
// that applications will eventually outgrow this middleware and replace it with
// a custom request logger, such as one that produces machine-parseable output,
// outputs logs to a different service (e.g., syslog), or formats lines like
// those printed elsewhere in the application.
func Logger(next chi.Handler) chi.Handler {
	fn := func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		reqID := GetReqID(ctx)

		printStart(reqID, r)

		lw := wrapWriter(w)

		t1 := time.Now()
		next.ServeHTTPC(ctx, lw, r)

		if lw.Status() == 0 {
			lw.WriteHeader(http.StatusOK)
		}
		t2 := time.Now()

		printEnd(reqID, lw, t2.Sub(t1))
	}

	return chi.HandlerFunc(fn)
}