router

package module
v1.5.1 Latest Latest
Warning

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

Go to latest
Published: Jan 19, 2018 License: MIT Imports: 13 Imported by: 10

README

router

A router which allows pattern matching, routes, redirects, filters and provides a handler interface. This router is now deprecated, use fragmenta mux instead as in the example fragmenta/cms app, this requires changing the handler signature to one closer to the net/http standard library, and using a simpler context object.

Usage

Setup the router

	// Routing
	router, err := router.New(server.Logger, server)
	if err != nil {
		server.Fatalf("Error creating router %s", err)
	}

Add a route with named parameters, matching a regexp, and a method if necessary

	r.Add("/tags/{id:[0-9]+}/destroy", tagactions.HandleDestroy).Post()
ContextHandler interface

The router handlers accept a context (which wraps Writer and Request, and provides some other functions), and return an error for easier error handling. The error may contain status codes and other details of the error for reporting in development environments.

	// Setup server
	server, err := server.New()
	if err != nil {
		fmt.Printf("Error creating server %s", err)
		return
	}

	// Write to log 
	server.Logf("#info Starting server in %s mode on port %d", server.Mode(), server.Port())

	// Start the server
	err = server.Start()
	if err != nil {
		server.Fatalf("Error starting server %s", err)
	}

Documentation

Overview

Package router provides a router linking uris to handlers taking a context

Package router provides a router linking uris to handlers taking a context

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Redirect

func Redirect(context Context, path string) error

Redirect uses status 302 StatusFound by default - this is not a permanent redirect We don't accept external or relative paths for security reasons

func RedirectExternal

func RedirectExternal(context Context, path string) error

RedirectExternal redirects setting the status code (for example unauthorized), but does no checks on the path Use with caution and only on completely known paths.

func RedirectStatus

func RedirectStatus(context Context, path string, status int) error

RedirectStatus redirects setting the status code (for example unauthorized) We don't accept external or relative paths for security reasons

Types

type ConcreteContext

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

ConcreteContext is the request context, including a writer, the current request etc

func (*ConcreteContext) Config

func (c *ConcreteContext) Config(key string) string

Config returns a key from the context config

func (*ConcreteContext) Get

func (c *ConcreteContext) Get(key string) interface{}

Get retreives arbitrary data for this request

func (*ConcreteContext) Header

func (c *ConcreteContext) Header() http.Header

Header calls our writer and returns the header map that will be sent by WriteHeader.

func (*ConcreteContext) Log

func (c *ConcreteContext) Log(message string)

Log logs the given message using our logger

func (*ConcreteContext) Logf

func (c *ConcreteContext) Logf(format string, v ...interface{})

Logf logs the given message and arguments using our logger

func (*ConcreteContext) Param

func (c *ConcreteContext) Param(key string) string

Param retreives a single param value, ignoring multiple values This may trigger a parse of the request and route

func (*ConcreteContext) ParamFiles

func (c *ConcreteContext) ParamFiles(key string) ([]*multipart.FileHeader, error)

ParamFiles parses the request as multipart, and then returns the file parts for this key NB it calls ParseMultipartForm prior to reading the parts

func (*ConcreteContext) ParamInt

func (c *ConcreteContext) ParamInt(key string) int64

ParamInt retreives a single param value as int, ignoring multiple values This may trigger a parse of the request and route

func (*ConcreteContext) Params

func (c *ConcreteContext) Params() (Params, error)

Params loads and return all the params from the request

func (*ConcreteContext) Path

func (c *ConcreteContext) Path() string

Path returns the path for the request

func (*ConcreteContext) Production

func (c *ConcreteContext) Production() bool

Production returns whether this context is running in production

func (*ConcreteContext) RenderContext

func (c *ConcreteContext) RenderContext() map[string]interface{}

RenderContext returns a context for rendering the view

func (*ConcreteContext) Request

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

Request returns the current http Request

func (*ConcreteContext) Route

func (c *ConcreteContext) Route() *Route

Route returns the route handling this request

func (*ConcreteContext) Set

func (c *ConcreteContext) Set(key string, data interface{})

Set saves arbitrary data for this request

func (*ConcreteContext) Write

func (c *ConcreteContext) Write(b []byte) (int, error)

Write calls our writer and writes the data to the connection as part of an HTTP reply.

func (*ConcreteContext) WriteHeader

func (c *ConcreteContext) WriteHeader(i int)

WriteHeader calls our writer and sends an HTTP response header with status code.

func (*ConcreteContext) Writer

func (c *ConcreteContext) Writer() http.ResponseWriter

Writer returns the http.ResponseWriter for responding to the request

type Config

type Config interface {
	Production() bool
	Config(string) string
}

Config Interface to retreive configuration details of the server

type Context

type Context interface {
	// Context acts as a facade on responseWriter
	http.ResponseWriter

	// Request returns the http.Request embedded in this context
	Request() *http.Request

	// Writer returns the http.ResponseWriter embedded in this context
	Writer() http.ResponseWriter

	// Request returns the cleaned path for this request
	Path() string

	// Route returns the route handling for this request
	Route() *Route

	// Config returns a key from the context config
	Config(key string) string

	// Production returns true if we are running in a production environment
	Production() bool

	// Params returns all params for a request
	Params() (Params, error)

	// Param returns a key from the request params
	Param(key string) string

	// ParamInt returns an int64 key from the request params
	ParamInt(key string) int64

	// ParamFiles parses the request as multipart, and then returns the file parts for this key
	ParamFiles(key string) ([]*multipart.FileHeader, error)

	// Store arbitrary data for this request
	Set(key string, data interface{})

	// Retreive arbitrary data for this request
	Get(key string) interface{}

	// Return the rendering context (our data)
	RenderContext() map[string]interface{}

	// Log a message
	Log(message string)

	// Log a format and arguments
	Logf(format string, v ...interface{})
}

Context is a request context wrapping a response writer and the request details

func NewContext added in v1.5.1

func NewContext(writer http.ResponseWriter, request *http.Request, route *Route, config Config, logger Logger) Context

NewContext returns a new context this should also be used in the Handle function and tests FIXME

type ErrHandler

type ErrHandler func(Context, error)

ErrHandler is used to render a router.Error - used by ErrorHandler on the router

type Handler

type Handler func(Context) error

Handler is our standard handler function, accepting a router.Context interface, and returning router.Error

type Logger

type Logger interface {
	Printf(format string, args ...interface{})
}

Logger Interface for a simple logger (the stdlib log pkg and the fragmenta log pkg conform)

type Params

type Params map[string][]string

Params is similar to url.Values, but with a few more utility functions

func (Params) Add

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

Add adds the value, if necessary appending to any existing values associated with key.

func (Params) Blank

func (p Params) Blank(key string) bool

Blank returns true if the value corresponding to key is an empty string

func (Params) Clean added in v1.3.3

func (p Params) Clean(accepted []string) map[string]string

Clean returns the params as a map[string]string, discarding any multiple values, with any params not in the accepted list removed

func (Params) Flatten

func (p Params) Flatten(k string) string

Flatten deflates a set of params (of any type) to a comma separated list (only for simple params)

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 returns the empty string.

func (Params) GetAll

func (p Params) GetAll(key string) []string

GetAll returns all values associated with the given key - equivalent to params[key].

func (Params) GetDate

func (p Params) GetDate(key string, format string) (time.Time, error)

GetDate returns the first value associated with a given key as a time, using the given time format.

func (Params) GetFloat added in v1.3.3

func (p Params) GetFloat(key string) float64

GetFloat returns the first value associated with the given key as an integer. If there is no value or a parse error, it returns 0.0

func (Params) GetFloats added in v1.3.3

func (p Params) GetFloats(key string) []float64

GetFloats returns all values associated with the given key as an array of floats.

func (Params) GetInt

func (p Params) GetInt(key string) int64

GetInt returns the first value associated with the given key as an integer. If there is no value or a parse error, it returns 0 If the string contains non-numeric characters, they are first stripped

func (Params) GetInts

func (p Params) GetInts(key string) []int64

GetInts returns all values associated with the given key as an array of integers.

func (Params) GetIntsString

func (p Params) GetIntsString(key string) string

GetIntsString returns all values associated with the given key as a comma separated string

func (Params) GetUniqueInts

func (p Params) GetUniqueInts(key string) []int64

GetUniqueInts returns all unique non-zero int values associated with the given key as an array of integers

func (Params) Map

func (p Params) Map() map[string]string

Map gets the params as a flat map[string]string, discarding any multiple values.

func (Params) Remove

func (p Params) Remove(key string)

Remove deletes the values associated with key.

func (Params) Set

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

Set sets the key to a string value replacing any existing values.

func (Params) SetInt

func (p Params) SetInt(key string, value int64)

SetInt sets the key to a single int value as string replacing any existing values.

type Route

type Route struct {
	// An HTTP handler which accepts a context
	Handler Handler

	// If the route is simply a string we match against that
	Pattern string

	// Up to three letters to match (before any regexp) for fast decisions on matches
	PatternShort string

	// If the route is a regexp, we match that instead (this may have groups etc)
	Regexp *regexp.Regexp

	// Param names taken from the Pattern and matching params
	ParamNames []string

	// Redirect path - used to redirect if handler is nil
	RedirectPath string

	// Redirect status - used to redirect if handler is nil
	RedirectStatus int
	// contains filtered or unexported fields
}

Route stores information to match a request and build URLs.

func NewRoute

func NewRoute(pattern string, handler Handler) (*Route, error)

NewRoute creates a new Route, given a pattern to match and a handler for the route

func (*Route) Accept

func (r *Route) Accept(method string) *Route

Accept allows the method provided

func (*Route) Delete

func (r *Route) Delete() *Route

Delete sets the method exclusively to DELETE

func (*Route) Get

func (r *Route) Get() *Route

Get sets the method exclusively to GET

func (*Route) MatchMethod

func (r *Route) MatchMethod(method string) bool

MatchMethod returns true if our list of methods contains method

func (*Route) MatchPath

func (r *Route) MatchPath(path string) bool

MatchPath returns true if this route matches the path

func (*Route) Method

func (r *Route) Method(method string) *Route

Method sets the method exclusively to method

func (*Route) Methods

func (r *Route) Methods(permitted ...string) *Route

Methods sets the methods allowed as an array

func (*Route) Parse

func (r *Route) Parse(path string) map[string]string

Parse reads our params using the regexp from the given path

func (*Route) Post

func (r *Route) Post() *Route

Post sets the method exclusively to POST

func (*Route) Put

func (r *Route) Put() *Route

Put sets the method exclusively to PUT

func (*Route) String

func (r *Route) String() string

String returns the route formatted as a string

type Router

type Router struct {

	// File handler (sends files)
	FileHandler Handler

	// Error handler (renders errors)
	ErrorHandler ErrHandler

	// The logger passed to actions within the context on each request
	Logger Logger

	// The server config passed to actions within the context on each request
	Config Config
	// contains filtered or unexported fields
}

Router stores and handles the routes

func New

func New(l Logger, s Config) (*Router, error)

New creates a new router

func (*Router) Add

func (r *Router) Add(pattern string, handler Handler) *Route

Add a new route

func (*Router) AddFilter

func (r *Router) AddFilter(filter Handler)

AddFilter adds a new filter to our list of filters to execute before request handlers

func (*Router) AddFilterHandler

func (r *Router) AddFilterHandler(handler http.Handler)

AddFilterHandler adds a standard http.Handler to filters wrapped in a ContextHandler

func (*Router) AddFilterHandlerFunc

func (r *Router) AddFilterHandlerFunc(handler http.HandlerFunc)

AddFilterHandlerFunc adds a standard http.HandlerFunc to filters wrapped in a ContextHandler

func (*Router) AddRedirect

func (r *Router) AddRedirect(pattern string, redirectPath string, status int) *Route

AddRedirect adds a new redirect this is just a route with a redirect path set

func (*Router) Log

func (r *Router) Log(message string)

Log this format and arguments

func (*Router) Logf

func (r *Router) Logf(format string, v ...interface{})

Logf logs this message and the given arguments

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(writer http.ResponseWriter, request *http.Request)

ServeHTTP - Central dispatcher for web requests - sets up the context and hands off to handlers

type StatusError

type StatusError struct {
	Err     error
	Status  int
	Title   string
	Message string
	File    string
	Line    int
}

StatusError wraps a std error and stores more information (status code, display title/msg and caller info)

func BadRequestError

func BadRequestError(e error, args ...string) *StatusError

BadRequestError returns a new StatusError with Status StatusBadRequest and optional Title and Message

func Error

func Error(e error, s int, t string, m string) *StatusError

Error returns a new StatusError with code StatusInternalServerError and a generic message

func InternalError

func InternalError(e error, args ...string) *StatusError

InternalError returns a new StatusError with Status StatusInternalServerError and optional Title and Message Usage: return router.InternalError(err)

func NotAuthorizedError

func NotAuthorizedError(e error, args ...string) *StatusError

NotAuthorizedError returns a new StatusError with Status StatusUnauthorized and optional Title and Message

func NotFoundError

func NotFoundError(e error, args ...string) *StatusError

NotFoundError returns a new StatusError with Status StatusNotFound and optional Title and Message Usage return router.NotFoundError(err,"Optional Title", "Optional user-friendly Message")

func ToStatusError

func ToStatusError(e error) *StatusError

ToStatusError returns a *StatusError or wraps a standard error in a 500 StatusError

func (*StatusError) Error

func (e *StatusError) Error() string

Error returns the underling error string - it should not be shown in production

func (*StatusError) FileLine

func (e *StatusError) FileLine() string

FileLine returns file name and line of error

func (*StatusError) String

func (e *StatusError) String() string

String returns a string represenation of this error, useful for debugging

Jump to

Keyboard shortcuts

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