| OLD | NEW |
| (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_test |
| 6 |
| 7 import ( |
| 8 "fmt" |
| 9 "io/ioutil" |
| 10 "math/rand" |
| 11 "net/http" |
| 12 "net/http/httptest" |
| 13 |
| 14 "golang.org/x/net/context" |
| 15 |
| 16 "github.com/luci/luci-go/server/router" |
| 17 ) |
| 18 |
| 19 func Logger(c *router.Context, next router.Handler) { |
| 20 fmt.Println(c.Request.URL) |
| 21 next(c) |
| 22 } |
| 23 |
| 24 func AuthCheck(c *router.Context, next router.Handler) { |
| 25 var authenticated bool |
| 26 if !authenticated { |
| 27 c.Writer.WriteHeader(http.StatusUnauthorized) |
| 28 c.Writer.Write([]byte("Authentication failed")) |
| 29 return |
| 30 } |
| 31 next(c) |
| 32 } |
| 33 |
| 34 func GenerateSecret(c *router.Context, next router.Handler) { |
| 35 c.Context = context.WithValue(c.Context, "secret", rand.Int()) |
| 36 next(c) |
| 37 } |
| 38 |
| 39 func makeRequest(client *http.Client, url string) string { |
| 40 res, err := client.Get(url + "/") |
| 41 if err != nil { |
| 42 panic(err) |
| 43 } |
| 44 defer res.Body.Close() |
| 45 p, err := ioutil.ReadAll(res.Body) |
| 46 if err != nil { |
| 47 panic(err) |
| 48 } |
| 49 if len(p) == 0 { |
| 50 return fmt.Sprintf("%d", res.StatusCode) |
| 51 } |
| 52 return fmt.Sprintf("%d %s", res.StatusCode, p) |
| 53 } |
| 54 |
| 55 func makeRequests(url string) { |
| 56 c := &http.Client{} |
| 57 fmt.Println(makeRequest(c, url+"/hello")) |
| 58 fmt.Println(makeRequest(c, url+"/hello/darknessmyoldfriend")) |
| 59 fmt.Println(makeRequest(c, url+"/authenticated/secret")) |
| 60 } |
| 61 |
| 62 // Example_createServer demonstrates creating an HTTP server using the router |
| 63 // package. |
| 64 func Example_createServer() { |
| 65 r := router.New() |
| 66 r.Use(router.MiddlewareChain{Logger}) |
| 67 r.GET("/hello", nil, func(c *router.Context) { |
| 68 fmt.Fprintf(c.Writer, "Hello") |
| 69 }) |
| 70 r.GET("/hello/:name", nil, func(c *router.Context) { |
| 71 fmt.Fprintf(c.Writer, "Hello %s", c.Params.ByName("name")) |
| 72 }) |
| 73 |
| 74 auth := r.Subrouter("authenticated") |
| 75 auth.Use(router.MiddlewareChain{AuthCheck}) |
| 76 auth.GET("/secret", router.MiddlewareChain{GenerateSecret}, func(c *rout
er.Context) { |
| 77 fmt.Fprintf(c.Writer, "secret: %d", c.Context.Value("secret")) |
| 78 }) |
| 79 |
| 80 server := httptest.NewServer(r) |
| 81 defer server.Close() |
| 82 |
| 83 makeRequests(server.URL) |
| 84 |
| 85 // Output: |
| 86 // /hello |
| 87 // 200 Hello |
| 88 // /hello/darknessmyoldfriend |
| 89 // 200 Hello darknessmyoldfriend |
| 90 // /authenticated/secret |
| 91 // 401 Authentication failed |
| 92 } |
| OLD | NEW |