route

package module
Version: v1.1.2 Latest Latest
Warning

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

Go to latest
Published: Mar 13, 2022 License: MIT Imports: 5 Imported by: 8

README

route docs

A HTTP request router.

  • Uses standard http.Handlers instead of a custom type.
  • Parameters, both single path segment "named" parameters and greedy "catch-all" parameters.
  • Allows overlapping route registrations, that is both /user/create and /user/:name may be registered.
  • Corrects trailing slashes and redirects paths with superfluous elements (e.g. ../, /./ and //).
  • A custom Not Found handler can be assigned.

parameters

A named parameter has the form :name where "name" is the key used to retrieve it from the map. Named parameters only match a single path segment:

Path: /blog/:category/:post

Requests:
 /blog/go/request-routers            match: category="go", post="request-routers"
 /blog/go/request-routers/           redirect to /blog/go/request-routers
 /blog/go/                           no match
 /blog/go/request-routers/comments   no match

A catch-all parameter has the form *name where "name" is the key used to retrieve it from the map. Catch-all parameters match everything including the preceeding "/", so must always be at the end of the pattern.

Path: /files/*filepath

Requests:
 /files/                             match: filepath=""
 /files/LICENSE                      match: filepath="LICENSE"
 /files/templates/article.html       match: filepath="templates/article.html"
 /files                              match: filepath=""

Parameters can be retrieved in handlers by calling route.Vars(*http.Request) map[string]string with the current request:

import (
  "fmt"
  "net/http"

  "hawx.me/code/route"
)

func greetingHandler(w http.ResponseWriter, r *http.Request)) {
  vars := route.Vars(r)
  fmt.Fprintf(w, "Hi %s", vars["name"])
}

func main() {
  route.HandleFunc("/greet/:name", greetingHandler)
  http.ListenAndServe(":8080", route.Default)
}

Documentation

Overview

Package route is a HTTP request router.

The router matches incoming requests by path to registered handlers. It should feel familiar to users of the net/http package.

The registered path may contain parameters, of which there are two types.

Named

Named parameters match single path segments. They match until the next '/' or the path end:

Path: /blog/:category/:post

Requests:
 /blog/go/request-routers            match: category="go", post="request-routers"
 /blog/go/request-routers/           redirect to /blog/go/request-routers
 /blog/go/                           no match
 /blog/go/request-routers/comments   no match

Catch-all

Catch-all parameters match anything until the path end. Since they match anything until the end, catch-all paramerters must always be the final path element.

Path: /files/*filepath

Requests:
 /files/                             match: filepath=""
 /files/LICENSE                      match: filepath="LICENSE"
 /files/templates/article.html       match: filepath="templates/article.html"
 /files                              match: filepath=""

The value of parameters is saved as a map[string]string against the request. To retrieve the parameters for a request use the Vars function:

vars := route.Vars(r)
Example
package main

import (
	"fmt"
	"log"
	"net/http"

	"hawx.me/code/route"
)

func Hello(w http.ResponseWriter, r *http.Request) error {
	vars := route.Vars(r)
	fmt.Fprintf(w, "hello, %s!\n", vars["name"])
	return nil
}

func main() {
	route.Handle("/", http.RedirectHandler("/hello/anon", http.StatusMovedPermanently))
	route.HandleFunc("/hello/:name", Hello)

	log.Fatal(http.ListenAndServe(":8080", route.Default))
}
Output:

Index

Examples

Constants

This section is empty.

Variables

View Source
var Default = New()

Default is the router instance used by the Handle and HandleFunc functions.

Functions

func Handle

func Handle(path string, handler interface{})

Handle registers the handler for the given path to the Default router.

func HandleFunc

func HandleFunc(path string, handler interface{})

HandleFunc registers the handler function for the given path to the Default router.

func Vars

func Vars(r *http.Request) map[string]string

Vars retrieves the parameter matches for the given request.

Types

type Handler added in v1.1.0

type Handler interface {
	ServeErrorHTTP(w http.ResponseWriter, r *http.Request) error
}

type HandlerFunc added in v1.1.0

type HandlerFunc func(w http.ResponseWriter, r *http.Request) error

func (HandlerFunc) ServeErrorHTTP added in v1.1.0

func (h HandlerFunc) ServeErrorHTTP(w http.ResponseWriter, r *http.Request) error

func (HandlerFunc) ServeHTTP added in v1.1.0

func (h HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request)

type Router

type Router struct {
	// NotFoundHandler is called when no matching route is found. By default it is
	// set to http.NotFoundHandler().
	NotFoundHandler http.Handler

	// ErrorHandler is called if an error is raised by any handler.
	ErrorHandler func(w http.ResponseWriter, r *http.Request, err error)
	// contains filtered or unexported fields
}

Router is a http.Handler which can be used to dispatch requests to different handler functions via configurable routes

func New

func New() *Router

New returns an initialized Router.

func (*Router) Handle

func (r *Router) Handle(path string, handle interface{})

Handle registers the handler for the given path to the router.

func (*Router) HandleFunc

func (r *Router) HandleFunc(path string, handler interface{})

HandleFunc registers the handler function (either `func(http.ResponseWriter, *http.Request)` or `func(http.ResponseWriter, *http.Request) error`) for the given path to the Default router.

func (*Router) ServeHTTP

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

ServeHTTP dispatches the request to appropriate handler, if none can be found NotFoundHandler is used.

Jump to

Keyboard shortcuts

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