Chromium Code Reviews| Index: server/router/example_test.go |
| diff --git a/server/router/example_test.go b/server/router/example_test.go |
| new file mode 100644 |
| index 0000000000000000000000000000000000000000..de0fcdc7b8e9b8590a179629eade52e37d837291 |
| --- /dev/null |
| +++ b/server/router/example_test.go |
| @@ -0,0 +1,75 @@ |
| +// 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_test |
| + |
| +import ( |
| + "fmt" |
| + "log" |
| + "math/rand" |
| + "net/http" |
| + "time" |
| + |
| + "golang.org/x/net/context" |
| + |
| + "github.com/luci/luci-go/server/router" |
| +) |
| + |
| +var durations []time.Duration |
| + |
| +func Logger(c *router.Context, next router.Handler) { |
| + log.Println(c.Request.URL.String()) |
| + next(c) |
| +} |
| + |
| +func Monitor(c *router.Context, next router.Handler) { |
| + start := time.Now() |
| + next(c) |
| + durations = append(durations, time.Since(start)) |
| +} |
| + |
| +func AuthCheck(c *router.Context, next router.Handler) { |
| + var authenticated bool |
| + if !authenticated { |
| + c.WriteHeader(http.StatusUnauthorized) |
| + return |
| + } |
| + next(c) |
| +} |
| + |
| +func GenerateRandom(c *router.Context, next router.Handler) { |
| + secret := rand.Int() |
| + c.Context = context.WithValue(c.Context, "secret", secret) |
| + next(c) |
| +} |
| + |
| +func Root(c *router.Context) { |
| + c.WriteHeader(http.StatusOK) |
| +} |
| + |
| +func Hello(c *router.Context) { |
| + name := c.Params[0].Value |
| + fmt.Fprintf(c, "Hello, %s", name) |
| +} |
| + |
| +func Random(c *router.Context) { |
| + s := c.Value("secret").(int) |
| + fmt.Fprintf(c, "secret: %d", s) |
| +} |
| + |
| +// Example_createServer demonstrates creating an HTTP server using the imported |
| +// router package. |
| +func Example_createServer() { |
| + r := router.New() |
| + r.Use(router.MiddlewareChain{Logger, Monitor}) |
| + r.GET("/", nil, Root) |
| + r.GET("/hello/:name", nil, Hello) |
| + |
| + auth := r.Subrouter("authenticated") |
| + auth.Use(router.MiddlewareChain{AuthCheck}) |
| + auth.GET("/random", router.MiddlewareChain{GenerateRandom}, Random) |
| + |
| + http.Handle("/", r) |
| + log.Fatal(http.ListenAndServe(":8080", nil)) |
|
iannucci
2016/06/16 00:54:24
I think you need
// Output:
// something
//
nishanths
2016/06/16 03:43:27
Cool, done. :)
If you have time, please check to
|
| +} |