routes

package module
v0.0.0-...-853bef2 Latest Latest
Warning

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

Go to latest
Published: Aug 16, 2013 License: MIT Imports: 9 Imported by: 48

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/bradrydzewski/routes

Getting Started

package main

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

func Whoami(w http.ResponseWriter, r *http.Request) {
    params := r.URL.Query()
    lastName := params.Get(":last")
    firstName := params.Get(":first")
    fmt.Fprintf(w, "you are %s %s", firstName, lastName)
}

func main() {
    mux := routes.New()
    mux.Get("/:last/:first", Whoami)

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

You can create routes for all http methods:

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

You can specify custom regular expressions for routes:

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

You can also create routes for static files:

pwd, _ := os.Getwd()
mux.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 apply filters to routes, which is useful for enforcing security, redirects, etc.

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

var FilterUser = func(w http.ResponseWriter, r *http.Request) {
	if r.URL.User == nil || r.URL.User.Username() != "admin" {
		http.Error(w, "", http.StatusUnauthorized)
	}
}

r.Filter(FilterUser)

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) {
	...
})

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:

mux := routes.New()

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

mux.Get("/foo", fooHandler)

Define a route with restful parameters in the path:

mux.Get("/:foo/:bar", func(w http.ResponseWriter, r *http.Request) {
	params := r.URL.Query()
	foo := params.Get(":foo")
	bar := params.Get(":bar")
	fmt.Fprintf(w, "%s %s", foo, bar)
})

The parameters are parsed from the URL, and appended to the Request URL's query parameters.

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

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

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

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

Index

Constants

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

Variables

This section is empty.

Functions

func ReadJson

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

ReadJson will 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 will parses the XML-encoded data in the http Request object and stores the result in the value pointed to by v.

func ServeFormatted

func ServeFormatted(w http.ResponseWriter, r *http.Request, v interface{})

ServeFormatted replies to the request with a formatted representation of resource v, in the format requested by the client specified in the Accept header.

func ServeJson

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

ServeJson replies to the request with a JSON representation of resource v.

func ServeXml

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

ServeXml replies to the request with an XML representation of resource v.

Types

type RouteMux

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

func New

func New() *RouteMux

func (*RouteMux) AddRoute

func (m *RouteMux) AddRoute(method string, pattern string, handler http.HandlerFunc)

Adds a new Route to the Handler

func (*RouteMux) Del

func (m *RouteMux) Del(pattern string, handler http.HandlerFunc)

Del adds a new Route for DELETE requests.

func (*RouteMux) Filter

func (m *RouteMux) Filter(filter http.HandlerFunc)

Filter adds the middleware filter.

func (*RouteMux) FilterParam

func (m *RouteMux) FilterParam(param string, filter http.HandlerFunc)

FilterParam adds the middleware filter iff the REST URL parameter exists.

func (*RouteMux) Get

func (m *RouteMux) Get(pattern string, handler http.HandlerFunc)

Get adds a new Route for GET requests.

func (*RouteMux) Patch

func (m *RouteMux) Patch(pattern string, handler http.HandlerFunc)

Patch adds a new Route for PATCH requests.

func (*RouteMux) Post

func (m *RouteMux) Post(pattern string, handler http.HandlerFunc)

Post adds a new Route for POST requests.

func (*RouteMux) Put

func (m *RouteMux) Put(pattern string, handler http.HandlerFunc)

Put adds a new Route for PUT requests.

func (*RouteMux) ServeHTTP

func (m *RouteMux) ServeHTTP(rw http.ResponseWriter, r *http.Request)

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

func (*RouteMux) Static

func (m *RouteMux) Static(pattern string, dir string)

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

Directories

Path Synopsis
exp
cookie/authcookie
Package authcookie implements creation and verification of signed authentication cookies.
Package authcookie implements creation and verification of signed authentication cookies.
routes
Package routes a simple http routing API for the Go programming language, compatible with the standard http.ListenAndServe function.
Package routes a simple http routing API for the Go programming language, compatible with the standard http.ListenAndServe function.

Jump to

Keyboard shortcuts

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