Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(199)

Unified Diff: server/router/handler.go

Issue 2043423004: Make HTTP middleware easier to use (Closed) Base URL: https://github.com/luci/luci-go@master
Patch Set: router: remove unecessary type assertion in tests Created 4 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View side-by-side diff with in-line comments
Download patch
Index: server/router/handler.go
diff --git a/server/router/handler.go b/server/router/handler.go
new file mode 100644
index 0000000000000000000000000000000000000000..1995436b910e4f401be501ed820886fbd1b0e041
--- /dev/null
+++ b/server/router/handler.go
@@ -0,0 +1,48 @@
+// Copyright 2016 The LUCI Authors. All rights reserved.
+// Use of this source code is governed under the Apache License, Version 2.0
+// that can be found in the LICENSE file.
+
+package router
+
+type (
Vadim Sh. 2016/06/16 22:47:14 nit: it's the first chunk of code that uses type (
nishanths 2016/06/16 23:33:00 Done.
+ // Handler is the type for all request handlers.
+ Handler func(*Context)
+
+ // Middleware is a function that accepts a shared context and the next
+ // function. Since Middleware is typically part of a chain of functions
+ // that handles an HTTP request, it must obey the following rules.
+ //
+ // - Middleware must call next if it has not written to the Context
+ // by the end of the function.
+ // - Middleware must not call next if it has written to the Context.
+ // - Middleware must not write to the Context after next is called and
+ // c.Written()==true.
+ // - Middleware may modify the embedded context before calling next.
+ Middleware func(c *Context, next Handler)
+
+ // MiddlewareChain is a list of Middleware.
+ MiddlewareChain []Middleware
+)
+
+// Run executes the middleware chain and final handler with the given context as
+// the initial context.
+func (mc MiddlewareChain) Run(c *Context, h Handler) {
+ run(c, mc, nil, h)
+}
+
+// run executes the middleware chains m and n, and the handler h using the
+// Context c as the initial context.
+func run(c *Context, m, n MiddlewareChain, h Handler) {
+ switch {
+ case len(m) > 0:
+ m[0](c, func(ctx *Context) {
+ run(ctx, m[1:], n, h)
+ })
+ case len(n) > 0:
+ n[0](c, func(ctx *Context) {
+ run(ctx, m, n[1:], h)
Vadim Sh. 2016/06/16 22:47:14 nit: run(ctx, nil, n[1:], h) (to make it clear th
nishanths 2016/06/16 23:33:00 Done.
+ })
+ default:
+ h(c)
+ }
+}
« no previous file with comments | « server/router/example_test.go ('k') | server/router/router.go » ('j') | server/router/router.go » ('J')

Powered by Google App Engine
This is Rietveld 408576698