routes

package
v0.0.0-...-8d54895 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 13, 2015 License: MIT Imports: 15 Imported by: 0

README

routes.go

a simple http routing API for the Go programming language

go get github.com/drone/routes

for more information see: http://gopkgdoc.appspot.com/pkg/github.com/drone/routes

Getting Started

package main

import (
    "fmt"
    "github.com/drone/routes"
    "net/http"
)

func foobar (w http.ResponseWriter, r *http.Request) {
	c := routes.NewContext(r)
	foo := c.Params.Get(":foo")
	bar := c.Params.Get(":bar")
	fmt.Fprintf(w, "%s %s", foo, bar)
}

func main() {
    r := routes.NewRouter()
    r.Get("/:bar/:foo", foobar)

    http.Handle("/", r)
    http.ListenAndServe(":8088", nil)
}
Route Examples

You can create routes for all http methods:

r.Get("/:param", handler)
r.Put("/:param", handler)
r.Post("/:param", handler)
r.Patch("/:param", handler)
r.Del("/:param", handler)

You can specify custom regular expressions for routes:

r.Get("/files/:param(.+)", handler)

You can also create routes for static files:

pwd, _ := os.Getwd()
r.Static("/static", pwd)

this will serve any files in /static, including files in subdirectories. For example /static/logo.gif or /static/style/main.css.

Filters / Middleware

You can implement route filters to do things like enforce security, set session variables, etc

You can, for example, filter all request to enforce some type of security:

r.Filter(func(rw http.ResponseWriter, r *http.Request) {
	if r.URL.User != "admin" {
		http.Error(w, "", http.StatusForbidden)
	}
})

You can also apply filters only when certain REST URL Parameters exist:

r.Get("/:id", handler)
r.Filter("id", func(rw http.ResponseWriter, r *http.Request) {
	c := routes.NewContext(r)
	id := c.Params.Get("id")

	// verify the user has access to the specified resource id
	user := r.URL.User.Username()
    if HasAccess(user, id) == false {
		http.Error(w, "", http.StatusForbidden)
	}
})

Helper Functions

You can use helper functions for serializing to Json and Xml. I found myself constantly writing code to serialize, set content type, content length, etc. Feel free to use these functions to eliminate redundant code in your app.

Helper function for serving Json, sets content type to application/json:

func handler(w http.ResponseWriter, r *http.Request) {
	mystruct := { ... }
    routes.ServeJson(w, &mystruct)
}

Helper function for serving Xml, sets content type to application/xml:

func handler(w http.ResponseWriter, r *http.Request) {
	mystruct := { ... }
    routes.ServeXml(w, &mystruct)
}

Helper function to serve Xml OR Json, depending on the value of the Accept header:

func handler(w http.ResponseWriter, r *http.Request) {
	mystruct := { ... }
    routes.ServeFormatted(w, r, &mystruct)
}

Documentation

Overview

Package routes a simple http routing API for the Go programming language, compatible with the standard http.ListenAndServe function.

Create a new route multiplexer:

r := routes.NewRouter()

Define a simple route with a given method (ie Get, Put, Post ...), path and http.HandleFunc.

r.Get("/foo", fooHandler)

Define a route with restful parameters in the path:

r.Get("/:foo/:bar", func(rw http.ResponseWriter, req *http.Request) {
	c := routes.NewContext(req)
	foo := c.Params.Get("foo")
	bar := c.Params.Get("bar")
	fmt.Fprintf(rw, "%s %s", foo, bar)
})

The parameters are parsed from the URL, and stored in the Request Context.

More control over the route's parameter matching is possible by providing a custom regular expression:

r.Get("/files/:file(.+)", handler)

To start the web server, use the standard http.ListenAndServe function, and provide the route multiplexer:

http.Handle("/", r)
http.ListenAndServe(":8000", nil)

Index

Constants

View Source
const (
	DELETE  = "DELETE"
	GET     = "GET"
	HEAD    = "HEAD"
	OPTIONS = "OPTIONS"
	PATCH   = "PATCH"
	POST    = "POST"
	PUT     = "PUT"
)

Variables

This section is empty.

Functions

func Error

func Error(w http.ResponseWriter, code int)

Error will terminate the http Request with the specified error code.

func ReadJson

func ReadJson(r *http.Request, v interface{}) error

ReadJson parses the JSON-encoded data in the http.Request object and stores the result in the value pointed to by v.

func ReadXml

func ReadXml(r *http.Request, v interface{}) error

ReadXml parses the XML-encoded data in the http.Request object and stores the result in the value pointed to by v.

func ServeJson

func ServeJson(w http.ResponseWriter, v interface{})

ServeJson writes the JSON representation of resource v to the http.ResponseWriter.

func ServeTemplate

func ServeTemplate(w http.ResponseWriter, name string, data map[string]interface{})

ServeTemplate applies the named template to the specified data map and writes the output to the http.ResponseWriter.

func ServeXml

func ServeXml(w http.ResponseWriter, v interface{})

ServeXml writes the XML representation of resource v to the http.ResponseWriter.

Types

type Context

type Context struct {
	// named parameters that are passed in via RESTful URL Parameters
	Params Params

	// named attributes that persist for the lifetime of the request
	Values Values
	// contains filtered or unexported fields
}

Context stores data for the duration of the http.Request

func NewContext

func NewContext(r *http.Request) *Context

Retruns the Context associated with the http.Request.

func (*Context) Request

func (c *Context) Request() *http.Request

Retruns the parent http.Request to which the context is bound.

type Params

type Params map[string]string

Params maps a string key to a list of values.

func (Params) Del

func (p Params) Del(key string)

Del deletes the values associated with key.

func (Params) Get

func (p Params) Get(key string) string

Get gets the first value associated with the given key. If there are no values associated with the key, Get returns the empty string.

func (Params) Set

func (p Params) Set(key, value string)

Set sets the key to value. It replaces any existing values.

type Router

type Router struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

func NewRouter

func NewRouter() *Router

func (*Router) AddRoute

func (r *Router) AddRoute(method string, pattern string, handler http.HandlerFunc)

Adds a new Route to the Handler

func (*Router) Del

func (r *Router) Del(pattern string, handler http.HandlerFunc)

Del adds a new Route for DELETE requests.

func (*Router) Filter

func (r *Router) Filter(filter http.HandlerFunc)

Filter adds the middleware filter.

func (*Router) FilterParam

func (r *Router) FilterParam(param string, filter http.HandlerFunc)

FilterParam adds the middleware filter iff the URL parameter exists.

func (*Router) Get

func (r *Router) Get(pattern string, handler http.HandlerFunc)

Get adds a new Route for GET requests.

func (*Router) Patch

func (r *Router) Patch(pattern string, handler http.HandlerFunc)

Patch adds a new Route for PATCH requests.

func (*Router) Post

func (r *Router) Post(pattern string, handler http.HandlerFunc)

Post adds a new Route for POST requests.

func (*Router) Put

func (r *Router) Put(pattern string, handler http.HandlerFunc)

Put adds a new Route for PUT requests.

func (*Router) ServeHTTP

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

Required by http.Handler interface. This method is invoked by the http server and will handle all page routing

func (*Router) Set

func (r *Router) Set(name string, value interface{})

Set stores the specified key / value pair.

func (*Router) SetEnv

func (r *Router) SetEnv(name, value string)

SetEnv stores the specified environment variable as a key / value pair. If the environment variable is not set the default value will be used

func (*Router) Static

func (r *Router) Static(pattern string, dir string)

Adds a new Route for Static http requests. Serves static files from the specified directory

func (*Router) Template

func (r *Router) Template(t *template.Template)

Template uses the provided template definitions.

func (*Router) TemplateFiles

func (r *Router) TemplateFiles(filenames ...string)

TemplateFiles parses the template definitions from the named files.

func (*Router) TemplateGlob

func (r *Router) TemplateGlob(pattern string)

TemplateGlob parses the template definitions from the files identified by the pattern, which must match at least one file.

type Values

type Values map[interface{}]interface{}

Values maps a string key to a list of values.

func (Values) Del

func (v Values) Del(key interface{})

Del deletes the values associated with key.

func (Values) Get

func (v Values) Get(key interface{}) interface{}

Get gets the value associated with the given key. If there are no values associated with the key, Get returns nil.

func (Values) GetStr

func (v Values) GetStr(key interface{}) interface{}

GetStr gets the value associated with the given key in string format. If there are no values associated with the key, Get returns an empty string.

func (Values) Set

func (v Values) Set(key, value interface{})

Set sets the key to value. It replaces any existing values.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL