Back to godoc.org

Package router

v0.0.0-...-133ef59
Latest Go to latest

The latest major version is .

Published: 1 day ago | License: Apache-2.0 | Module: go.chromium.org/luci

Overview

Package router provides an HTTP router with support for middleware and subrouters. It wraps around julienschmidt/httprouter.

Example (CreateServer)

Example_createServer demonstrates creating an HTTP server using the router package.

Code:

package main

import (
	"context"
	"fmt"
	"io/ioutil"
	"math/rand"
	"net/http"
	"net/http/httptest"

	"go.chromium.org/luci/server/router"
)

func Logger(c *router.Context, next router.Handler) {
	fmt.Println(c.Request.URL)
	next(c)
}

func AuthCheck(c *router.Context, next router.Handler) {
	var authenticated bool
	if !authenticated {
		c.Writer.WriteHeader(http.StatusUnauthorized)
		c.Writer.Write([]byte("Authentication failed"))
		return
	}
	next(c)
}

func GenerateSecret(c *router.Context, next router.Handler) {
	c.Context = context.WithValue(c.Context, "secret", rand.Int())
	next(c)
}

func makeRequest(client *http.Client, url string) string {
	res, err := client.Get(url + "/")
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()
	p, err := ioutil.ReadAll(res.Body)
	if err != nil {
		panic(err)
	}
	if len(p) == 0 {
		return fmt.Sprintf("%d", res.StatusCode)
	}
	return fmt.Sprintf("%d %s", res.StatusCode, p)
}

func makeRequests(url string) {
	c := &http.Client{}
	fmt.Println(makeRequest(c, url+"/hello"))
	fmt.Println(makeRequest(c, url+"/hello/darknessmyoldfriend"))
	fmt.Println(makeRequest(c, url+"/authenticated/secret"))
}

// Example_createServer demonstrates creating an HTTP server using the router
// package.
func main() {
	r := router.New()
	r.Use(router.NewMiddlewareChain(Logger))
	r.GET("/hello", router.MiddlewareChain{}, func(c *router.Context) {
		fmt.Fprintf(c.Writer, "Hello")
	})
	r.GET("/hello/:name", router.MiddlewareChain{}, func(c *router.Context) {
		fmt.Fprintf(c.Writer, "Hello %s", c.Params.ByName("name"))
	})

	auth := r.Subrouter("authenticated")
	auth.Use(router.NewMiddlewareChain(AuthCheck))
	auth.GET("/secret", router.NewMiddlewareChain(GenerateSecret), func(c *router.Context) {
		fmt.Fprintf(c.Writer, "secret: %d", c.Context.Value("secret"))
	})

	server := httptest.NewServer(r)
	defer server.Close()

	makeRequests(server.URL)

}
/hello
200 Hello
/hello/darknessmyoldfriend
200 Hello darknessmyoldfriend
/authenticated/secret
401 Authentication failed

Index

Examples

func RunMiddleware

func RunMiddleware(c *Context, mc MiddlewareChain, h Handler)

RunMiddleware executes the middleware chain and handlers with the given initial context. Useful to execute a chain of functions in tests.

type Context

type Context struct {
	Context     context.Context
	Writer      http.ResponseWriter
	Request     *http.Request
	Params      httprouter.Params
	HandlerPath string // the path with which the handler was registered
}

Context contains the context, response writer, request, and params shared across Middleware and Handler functions.

type Handler

type Handler func(*Context)

Handler is the type for all request handlers.

type Middleware

type Middleware func(c *Context, next Handler)

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
  the Context has been written to.
- Middleware may modify the embedded context before calling next.

type MiddlewareChain

type MiddlewareChain struct {
	// contains filtered or unexported fields
}

MiddlewareChain is an ordered collection of Middleware.

MiddlewareChain's zero value is a middleware chain with no Middleware. Allocating a MiddlewareChain with Middleware can be done with NewMiddlewareChain.

func NewMiddlewareChain

func NewMiddlewareChain(mw ...Middleware) (mc MiddlewareChain)

NewMiddlewareChain creates a new MiddlewareChain with the supplied Middleware entries.

func (MiddlewareChain) Extend

func (mc MiddlewareChain) Extend(mw ...Middleware) MiddlewareChain

Extend returns a new MiddlewareChain with the supplied Middleware appended to the end.

func (MiddlewareChain) ExtendFrom

func (mc MiddlewareChain) ExtendFrom(other MiddlewareChain) MiddlewareChain

ExtendFrom returns a new MiddlewareChain with the supplied MiddlewareChain appended to the end.

type Router

type Router struct {
	BasePath string
	// contains filtered or unexported fields
}

Router is the main type for the package. To create a Router, use New.

func New

func New() *Router

New creates a Router.

func NewWithRootContext

func NewWithRootContext(root context.Context) *Router

NewWithRootContext creates a router whose request contexts all inherit from the given context.

func (*Router) DELETE

func (r *Router) DELETE(path string, mc MiddlewareChain, h Handler)

DELETE is a shortcut for router.Handle("DELETE", path, mc, h)

func (*Router) GET

func (r *Router) GET(path string, mc MiddlewareChain, h Handler)

GET is a shortcut for router.Handle("GET", path, mc, h)

func (*Router) GetParams

func (r *Router) GetParams(method, path string) (httprouter.Params, bool)

GetParams parases the httprouter.Params from the supplied method and path.

If nothing is registered for method/path, GetParams will return false.

func (*Router) HEAD

func (r *Router) HEAD(path string, mc MiddlewareChain, h Handler)

HEAD is a shortcut for router.Handle("HEAD", path, mc, h)

func (*Router) Handle

func (r *Router) Handle(method, path string, mc MiddlewareChain, h Handler)

Handle registers a middleware chain and a handler for the given method and path. len(mc)==0 is allowed. See https://godoc.org/github.com/julienschmidt/httprouter for documentation on how the path may be formatted.

func (*Router) NotFound

func (r *Router) NotFound(mc MiddlewareChain, h Handler)

NotFound sets the handler to be called when no matching route is found.

func (*Router) OPTIONS

func (r *Router) OPTIONS(path string, mc MiddlewareChain, h Handler)

OPTIONS is a shortcut for router.Handle("OPTIONS", path, mc, h)

func (*Router) PATCH

func (r *Router) PATCH(path string, mc MiddlewareChain, h Handler)

PATCH is a shortcut for router.Handle("PATCH", path, mc, h)

func (*Router) POST

func (r *Router) POST(path string, mc MiddlewareChain, h Handler)

POST is a shortcut for router.Handle("POST", path, mc, h)

func (*Router) PUT

func (r *Router) PUT(path string, mc MiddlewareChain, h Handler)

PUT is a shortcut for router.Handle("PUT", path, mc, h)

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(rw http.ResponseWriter, req *http.Request)

ServeHTTP makes Router implement the http.Handler interface.

func (*Router) Subrouter

func (r *Router) Subrouter(relativePath string) *Router

Subrouter creates a new router with an updated base path. The new router copies middleware and configuration from the router it derives from.

func (*Router) Use

func (r *Router) Use(mc MiddlewareChain)

Use adds middleware chains to the group. The added middleware applies to all handlers registered on the router and to all handlers registered on routers that may be derived from the router (using Subrouter).

Package Files

Documentation was rendered with GOOS=linux and GOARCH=amd64.

Jump to identifier

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to identifier