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

Side by Side 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: Convert remaining source files 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 unified diff | Download patch
OLDNEW
(Empty)
1 // Copyright 2016 The LUCI Authors. All rights reserved.
2 // Use of this source code is governed under the Apache License, Version 2.0
3 // that can be found in the LICENSE file.
4
5 package router
6
7 // Handler is the type for all request handlers.
8 type Handler func(*Context)
9
10 // Middleware is a function that accepts a shared context and the next
11 // function. Since Middleware is typically part of a chain of functions
12 // that handles an HTTP request, it must obey the following rules.
13 //
14 // - Middleware must call next if it has not written to the Context
15 // by the end of the function.
16 // - Middleware must not call next if it has written to the Context.
17 // - Middleware must not write to the Context after next is called and
18 // the Context has been written to.
19 // - Middleware may modify the embedded context before calling next.
20 type Middleware func(c *Context, next Handler)
21
22 // MiddlewareChain is a list of Middleware.
23 type MiddlewareChain []Middleware
24
25 // run executes the middleware chains m and n and the handler h using
26 // c as the initial context. If a middleware in m or n is nil, run
27 // simply advances to the next middleware or handler. If h is nil, run
28 // panics.
29 func run(c *Context, m, n MiddlewareChain, h Handler) {
30 switch {
31 case len(m) > 0:
32 if m[0] != nil {
33 m[0](c, func(ctx *Context) { run(ctx, m[1:], n, h) })
34 } else {
35 run(c, m[1:], n, h)
36 }
37 case len(n) > 0:
38 if n[0] != nil {
39 n[0](c, func(ctx *Context) { run(ctx, nil, n[1:], h) })
40 } else {
41 run(c, nil, n[1:], h)
42 }
43 default:
44 h(c)
45 }
46 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698