httptools

package module
v1.2.1 Latest Latest
Warning

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

Go to latest
Published: Mar 20, 2014 License: MIT Imports: 6 Imported by: 5

README

Package httptools tries to augment the basic net/http package with functionality found in webframeworks without breaking the original API.

For details and examples, please see the documentation.

Build Status

Contrived example

r := httptools.NewRegexpSwitch(map[string]http.Handler{
	"/people/(.+)": httptools.L{
		httptools.SilentHandler(AuthenticationHandler),
		httptools.MethodSwitch{
			"GET": ListPeople,
			"PUT": http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
				vars := w.(httptools.VarsResponseWriter).Vars()
				AddNewPerson(vars["1"])
			})
		},
		SaveSessionHandler,
	},
	"/.+": http.FileServer(http.Dir("./static")),
})
http.ListenAndServe("localhost:8080", r)

Tools

httptools provides the following tools:

Handler list

Define a sequence of http.Handler. One will be executed after another. A customized http.ResponseWriter allows the passing of data in between handlers.

Silent handler

If a silent handler produces output, it is assumed to be an error. If the silent handler is in a handler list, the execution of the list will be aborted.

Switches

Method switch

Dispatch requests to different handlers according the the HTTP verb used in the request.

RegexpSwitch

Dispatch requests to different handlers according to regexps being matched agains the request path.

HostnameSwitch

Dispatch requests to different handlers according to the hostname used in the request.

Mounts

Dispatch requests to different handlers according to path prefixes. The path prefix will be stripped from the request before being passed to the handler.


Version 1.2.1

Documentation

Overview

Package httptools tries to augment the basic net/http package with functionality found in webframeworks without breaking the original API.

Index

Examples

Constants

View Source
const (
	VERSION = "1.2.1"
)

Variables

This section is empty.

Functions

func DiscardPathElements added in v1.2.0

func DiscardPathElements(n int) http.Handler

DiscardPathElements discards n elements from the request path. It's most useful in a handler list. The original request path can be found in the VarsResponseWriter under "OrigPath".

Example
ms := L{
	DiscardPathElements(2),
	http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Println(r.URL.Path)
	}),
}
req, _ := http.NewRequest("GET", "/prefix/and/a/real/path", nil)
ms.ServeHTTP(httptest.NewRecorder(), req)
req, _ = http.NewRequest("GET", "/", nil)
ms.ServeHTTP(httptest.NewRecorder(), req)
Output:

/a/real/path
/

func SilentHandler

func SilentHandler(h http.Handler) http.Handler

"Casts" the given handler into a silent handler. Silent handlers are expected to produce no output. If they do, it is assumend to be an error message/error code. In a HandlerList, this execution of the list will be aborted if a SilentHandler produces output.

func TrimPortNumber added in v1.1.0

func TrimPortNumber(host string) string

Types

type CheckResponseWriter

type CheckResponseWriter interface {
	http.ResponseWriter
	// Returns true if the headers have been written
	WasWritten() bool
}

CheckResponseWriter is a http.ResponseWriter which saves wether it has been written to or not.

type HostnameSwitch added in v1.1.0

type HostnameSwitch map[string]http.Handler

HostnameSwitch dispatches requests to different handlers depending on the value of r.Host. If no appropriate handler is found, the handler with the "_" key will be used. Otherwise, a 404 is returned. Port numbers in the request will be stripped before matching.

func (HostnameSwitch) ServeHTTP added in v1.1.0

func (hs HostnameSwitch) ServeHTTP(w http.ResponseWriter, r *http.Request)

type L

type L []http.Handler

A handler list is a list of http.Handlers which are executed sequentially. If a handler is a SilentHandler and it produces output (i.e. calls WriteHeader()), it is assumed to be an error message/error code and executing the remaining handlers in the list will be skipped. The ResponseWriter will be an VarsResponseWriter to make data passing between handlers more convenient.

func (L) ServeHTTP

func (l L) ServeHTTP(w http.ResponseWriter, r *http.Request)

type MethodSwitch

type MethodSwitch map[string]http.Handler

MethodSwitch dispatches request to different handlers depending on the HTTP verb used in the request.

Example
ms := MethodSwitch{
	"GET": http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Println("A GET request")
	}),
	"POST": http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Println("A POST request")
	}),
}
req, _ := http.NewRequest("GET", "/", nil)
ms.ServeHTTP(httptest.NewRecorder(), req)
req, _ = http.NewRequest("POST", "/", nil)
ms.ServeHTTP(httptest.NewRecorder(), req)
Output:

A GET request
A POST request

func (MethodSwitch) ServeHTTP

func (ms MethodSwitch) ServeHTTP(w http.ResponseWriter, r *http.Request)

type Mounts added in v1.1.0

type Mounts map[string]http.Handler

Mounts is a list of handlers which are mounted at the given path. Mounting is a simple path prefix-based routing. The prefix will be stripped from the request before being passed to the associated handler. The original request path will available in the VarsResponseWriter under "OrigPath".

Example
ms := Mounts{
	"/api/": Mounts{
		"/cars": http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			fmt.Println("Request path:", r.URL.Path)
			fmt.Println("Original path:", w.(VarsResponseWriter).Vars()["OrigPath"].(string))
		}),
		"/people": http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			// ...
		}),
	},
}
req, _ := http.NewRequest("GET", "/api/cars/bentley", nil)
ms.ServeHTTP(httptest.NewRecorder(), req)
Output:

Request path: /bentley
Original path: /api/cars/bentley

func (Mounts) ServeHTTP added in v1.1.0

func (m Mounts) ServeHTTP(w http.ResponseWriter, r *http.Request)

type RegexpRule added in v1.1.0

type RegexpRule interface {
	// Same method provided by regexp.Regexp.
	// The returned array will be saved to the VarsResponseWriter.
	FindStringSubmatch(s string) []string
	http.Handler
}

RegexpRule represents a single rule in a RegexpSwitch.

type RegexpSwitch added in v1.1.0

type RegexpSwitch []RegexpRule

RegexpSwitch dispatches requests to different handlers depending on regexp patterns the r.URL.Path matches. RegexpSwitch is a slice of RegexpRules. They will be checked in the order they have been provided. If a rule matches (i.e. Regexp.Rule.FindStringSubmatch return value is non-nil), the Handler will be called and the slice traversal is stopped.

func NewRegexpSwitch

func NewRegexpSwitch(routes map[string]http.Handler) RegexpSwitch

A regexp switch takes a map of regexp strings and handlers. A regexp is considered a match if it matches the whole string. Longer patterns take precedence over shorter ones.

Example
rr := NewRegexpSwitch(map[string]http.Handler{
	"/people/([a-z]+)": http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		vars := w.(VarsResponseWriter).Vars()
		fmt.Printf("You are looking for %s", vars["1"].(string))
	}),
})
req, _ := http.NewRequest("GET", "/people/peter", nil)
rr.ServeHTTP(httptest.NewRecorder(), req)
Output:

You are looking for peter

func (RegexpSwitch) ServeHTTP added in v1.1.0

func (rs RegexpSwitch) ServeHTTP(w http.ResponseWriter, r *http.Request)

type VarsResponseWriter

type VarsResponseWriter interface {
	http.ResponseWriter
	Vars() map[string]interface{}
}

VarsResponseWriter is a http.ResponseWriter which gives access to a map. The map can be filled with arbitrary data and is supposed to be out-of-band channel to pass data between handlers in a handler list or any kind of handler switch.

Jump to

Keyboard shortcuts

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