Documentation ¶
Overview ¶
Package mango is a routing object which implements the http.Handler interface. It has been designed primarily to facilitate the creation of HTTP based APIs and REST services.
It uses a context per request approach which enables simplified handlers, as much of the boiler plate work is done for you. The Context object takes care of tasks such as serialization/deserialization, respecting the Content-Type and Accept headers to ensure responses match the request. You can create and add your custom content-type encoders to suit your needs.
A radix-tree based routing system enables better response times and greater flexibility in the way routes are structured and added to the system. Parameter based patterns with constraint rules provide great flexibility, and custom rules can be added.
Hooks and other mechanisms exist to enable customisation in accordance with your specific application, such as authentication, database repository injection.
See the full documentation here https://github.com/spaceweasel/mango/wiki
Index ¶
- Constants
- type AlphaNumValidator
- type AlphaValidator
- type BasicIdentity
- type Browser
- func (b *Browser) Delete(url string, headers http.Header) (*httptest.ResponseRecorder, error)
- func (b *Browser) Get(url string, headers http.Header) (*httptest.ResponseRecorder, error)
- func (b *Browser) Head(url string, headers http.Header) (*httptest.ResponseRecorder, error)
- func (b *Browser) Options(url string, headers http.Header) (*httptest.ResponseRecorder, error)
- func (b *Browser) Patch(url string, body io.Reader, headers http.Header) (*httptest.ResponseRecorder, error)
- func (b *Browser) PatchS(url, body string, headers http.Header) (*httptest.ResponseRecorder, error)
- func (b *Browser) Post(url string, body io.Reader, headers http.Header) (*httptest.ResponseRecorder, error)
- func (b *Browser) PostS(url, body string, headers http.Header) (*httptest.ResponseRecorder, error)
- func (b *Browser) Put(url string, body io.Reader, headers http.Header) (*httptest.ResponseRecorder, error)
- func (b *Browser) PutS(url, body string, headers http.Header) (*httptest.ResponseRecorder, error)
- type CORSConfig
- type ContainsValidator
- type Context
- func (c *Context) Authenticated() bool
- func (c *Context) Bind(m interface{}) error
- func (c *Context) Error(msg string, code int)
- func (c *Context) GetEncoder() (Encoder, string, error)
- func (c *Context) Redirect(urlStr string, code int)
- func (c *Context) Respond() *Response
- func (c *Context) RespondWith(d interface{}) *Response
- func (c *Context) Validate(m interface{}) (map[string][]ValidationFailure, bool)
- type ContextHandlerFunc
- type Decoder
- type DecoderFunc
- type DigitsValidator
- type EmailValidator
- type EmptyValidator
- type Encoder
- type EncoderEngine
- type EncoderFunc
- type Hex32Validator
- type Hex64Validator
- type HexValidator
- type Identity
- type InSetValidator
- type Int32Validator
- type Int64Validator
- type LenMaxValidator
- type LenMinValidator
- type LenRangeValidator
- type MaxValidator
- type MinValidator
- type ModelValidator
- type NotEmptyOrWhitespaceValidator
- type NotEmptyValidator
- type NotNilValidator
- type NotWhitespaceValidator
- type NotZeroValidator
- type PhoneValidator
- type PrefixValidator
- type RangeValidator
- type Registerer
- type RequestLog
- type RequestLogFunc
- type Resource
- type Response
- type ResponseWriter
- type Router
- func (r *Router) AddCORS(pattern string, config CORSConfig)
- func (r *Router) AddModelValidator(m interface{}, fn ValidateFunc)
- func (r *Router) AddPostHook(hook ContextHandlerFunc)
- func (r *Router) AddPreHook(hook ContextHandlerFunc)
- func (r *Router) Delete(pattern string, handlerFunc ContextHandlerFunc)
- func (r *Router) Get(pattern string, handlerFunc ContextHandlerFunc)
- func (r *Router) Head(pattern string, handlerFunc ContextHandlerFunc)
- func (r *Router) Options(pattern string, handlerFunc ContextHandlerFunc)
- func (r *Router) Patch(pattern string, handlerFunc ContextHandlerFunc)
- func (r *Router) Post(pattern string, handlerFunc ContextHandlerFunc)
- func (r *Router) Put(pattern string, handlerFunc ContextHandlerFunc)
- func (r *Router) RegisterModules(modules []Registerer)
- func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)
- func (r *Router) SetCORS(pattern string, config CORSConfig)
- func (r *Router) SetGlobalCORS(config CORSConfig)
- func (r *Router) StaticDir(root string)
- type SentenceValidator
- type SuffixValidator
- type UUIDValidator
- type UnsupportedMediaTypeError
- type ValidateFunc
- type ValidationFailure
- type ValidationHandler
- type Validator
Examples ¶
Constants ¶
const ( // DefaultMediaType is the default media type that will be used // to encode response data if no other type is specified in the // request Accept header. // This default type can be overridden by calling the // SetDefaultMediaType method DefaultMediaType = "application/json" )
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type AlphaNumValidator ¶
type AlphaNumValidator struct{}
AlphaNumValidator tests for a sequence containing only alphanumeric characters.
func (*AlphaNumValidator) FailureMsg ¶
func (v *AlphaNumValidator) FailureMsg() string
FailureMsg returns a string with a readable message about the validation failure.
func (*AlphaNumValidator) Type ¶
func (v *AlphaNumValidator) Type() string
Type returns the constraint name (alphanum).
func (*AlphaNumValidator) Validate ¶
func (v *AlphaNumValidator) Validate(val interface{}, params []string) bool
Validate tests for alphanumeric values. Returns true if val is a string containing only characters in the ranges a-z, A-Z or 0-9. Validate panics if val is not a string.
type AlphaValidator ¶
type AlphaValidator struct{}
AlphaValidator tests for a sequence containing only alpha characters.
func (*AlphaValidator) FailureMsg ¶
func (v *AlphaValidator) FailureMsg() string
FailureMsg returns a string with a readable message about the validation failure.
func (*AlphaValidator) Type ¶
func (v *AlphaValidator) Type() string
Type returns the constraint name (alpha).
func (*AlphaValidator) Validate ¶
func (v *AlphaValidator) Validate(val interface{}, params []string) bool
Validate tests for alpha values. Returns true if val is a string containing only characters in the ranges a-z or A-Z. Validate panics if val is not a string.
type BasicIdentity ¶
type BasicIdentity struct {
Username string
}
BasicIdentity is a basic implementation of the Identity interface.
func (BasicIdentity) Email ¶
func (i BasicIdentity) Email() string
Email returns the email address of the request user
func (BasicIdentity) Fullname ¶
func (i BasicIdentity) Fullname() string
Fullname returns the fullname of the request user
func (BasicIdentity) Organization ¶
func (i BasicIdentity) Organization() string
Organization returns the organization of the request user
func (BasicIdentity) UserID ¶
func (i BasicIdentity) UserID() string
UserID returns the ID of the request user
type Browser ¶
type Browser struct {
// contains filtered or unexported fields
}
Browser is client used to simulate HTTP request to the service. This can be useful for verifying routings, testing request headers, as well as examining responses: headers, status code, content.
func NewBrowser ¶
NewBrowser returns a *Browser which can be used to test server responses. This method takes a Router as a parameter to enable full and accurate testing/simulation to be performed.
func (*Browser) Delete ¶
Delete simulates an HTTP DELETE request to the server. The response can be examined afterwards to check status, headers and content.
func (*Browser) Get ¶
Get simulates an HTTP GET request to the server. The response can be examined afterwards to check status, headers and content.
func (*Browser) Head ¶
Head simulates an HTTP HEAD request to the server. The response can be examined afterwards to check status, headers and content.
func (*Browser) Options ¶
Options simulates an HTTP OPTIONS request to the server. The response can be examined afterwards to check status, headers and content.
func (*Browser) Patch ¶
func (b *Browser) Patch(url string, body io.Reader, headers http.Header) (*httptest.ResponseRecorder, error)
Patch simulates an HTTP PATCH request to the server, with a string body.. The response can be examined afterwards to check status, headers and content.
func (*Browser) PatchS ¶
PatchS simulates an HTTP PATCH request to the server, with a string body.. The response can be examined afterwards to check status, headers and content.
func (*Browser) Post ¶
func (b *Browser) Post(url string, body io.Reader, headers http.Header) (*httptest.ResponseRecorder, error)
Post simulates an HTTP POST request to the server. The response can be examined afterwards to check status, headers and content.
func (*Browser) PostS ¶
PostS simulates an HTTP POST request to the server, with a string body. The response can be examined afterwards to check status, headers and content.
type CORSConfig ¶
type CORSConfig struct { // Origins list all permitted origins. A CORS request // origin MUST be in the Origins list for the response // headers to be populated with the correct response. // Values must contain the scheme (e.g. http://here.com). // A wildcard * can be used which will match ALL origins, // however the Access-Control-Allow-Origin response header // will always echo the request Origin if the remaining CORS // criteria is met. Origins []string // Methods available for the resource. If there are methods // listed here for which there is no handler, then that // method will not be included in the Access-Control-Allow-Methods // response header. Methods []string // Headers lists the custom headers in a request that the // server will accept Headers []string // ExposedHeaders are custom headers that the client browser // is allowed to access ExposedHeaders []string // Credentials controls the Access-Control-Allow-Credentials header. // The header is only included in the response if Credentials is true, // in which case the header has a value of "true". // A value of true allows the client browser to access response cookies. Credentials bool // MaxAge is the cache duration (in seconds) that is returned // in a Preflight Access-Control-Max-Age response header. // A value of zero means the header won't be sent. MaxAge int }
CORSConfig holds CORS configuration. It can be used as the configuration for an individual resource or as a global configuration for the entire router tree.
Example ¶
// Simple Request using Test Browser r := NewRouter() r.SetGlobalCORS(CORSConfig{ Origins: []string{"*"}, Methods: []string{"POST", "PUT"}, Headers: []string{"X-Mangoes"}, ExposedHeaders: []string{"X-Mangoes"}, }) r.Get("/fruits", func(c *Context) { c.RespondWith("GET fruits") }) br := NewBrowser(r) hdrs := http.Header{} hdrs.Set("Origin", "http://bluecheese.com") resp, err := br.Get("http://greencheese.com/fruits", hdrs) if err != nil { fmt.Println(err) return } allowOrigin := resp.HeaderMap.Get("Access-Control-Allow-Origin") exposedHeaders := resp.HeaderMap.Get("Access-Control-Expose-Headers") fmt.Println(allowOrigin) fmt.Println(exposedHeaders)
Output: http://bluecheese.com X-Mangoes
Example (Second) ¶
// Preflight Request using Test Browser r := NewRouter() r.SetGlobalCORS(CORSConfig{ Origins: []string{"http://bluecheese.com"}, Methods: []string{"POST", "PUT"}, Headers: []string{"X-Mangoes"}, ExposedHeaders: []string{"X-Mangoes"}, }) r.Post("/fruits", func(c *Context) { c.RespondWith("POST fruits") }) r.Get("/fruits", func(c *Context) { c.RespondWith("GET fruits") }) br := NewBrowser(r) hdrs := http.Header{} hdrs.Set("Origin", "http://bluecheese.com") hdrs.Set("Access-Control-Request-Method", "POST") hdrs.Set("Access-Control-Request-Headers", "X-Mangoes") resp, err := br.Options("http://greencheese.com/fruits", hdrs) if err != nil { fmt.Println(err) return } // Examine the response headers... allowOrigin := resp.HeaderMap.Get("Access-Control-Allow-Origin") allowMethods := strings.Join(resp.HeaderMap["Access-Control-Allow-Methods"], ",") allowHeaders := resp.HeaderMap.Get("Access-Control-Allow-Headers") vary := resp.HeaderMap.Get("Vary") fmt.Println(allowOrigin) // http://bluecheese.com fmt.Println(allowMethods) // GET,POST (PUT has no handler, so is removed from list) fmt.Println(allowHeaders) // X-Mangoes fmt.Println(vary) // Origin fmt.Println(resp.Code) // 200 fmt.Println(resp.Body) // Body should be empty
Output: http://bluecheese.com GET,POST X-Mangoes Origin 200
Example (Third) ¶
// Preflight Request using Test Browser // Still returns status 200 even though preflight check fails r := NewRouter() r.SetGlobalCORS(CORSConfig{ Origins: []string{"http://bluecheese.com"}, Methods: []string{"POST", "PUT"}, Headers: []string{"X-Mangoes"}, ExposedHeaders: []string{"X-Mangoes"}, }) r.Post("/fruits", func(c *Context) { c.RespondWith("POST fruits") }) r.Get("/fruits", func(c *Context) { c.RespondWith("GET fruits") }) br := NewBrowser(r) hdrs := http.Header{} hdrs.Set("Origin", "http://bluecheese.com") hdrs.Set("Access-Control-Request-Method", "PATCH") hdrs.Set("Access-Control-Request-Headers", "X-Mangoes") resp, err := br.Options("http://greencheese.com/fruits", hdrs) if err != nil { fmt.Println(err) return } // Examine the response headers... allowOrigin := resp.HeaderMap.Get("Access-Control-Allow-Origin") allowMethods := resp.HeaderMap.Get("Access-Control-Allow-Methods") allowHeaders := resp.HeaderMap.Get("Access-Control-Allow-Headers") vary := resp.HeaderMap.Get("Vary") // preflight check fails so all but the Resp.Code will be empty fmt.Println(allowOrigin) fmt.Println(allowMethods) fmt.Println(allowHeaders) fmt.Println(vary) fmt.Println(resp.Code) // 200 fmt.Println(resp.Body)
Output: 200
type ContainsValidator ¶
type ContainsValidator struct {
// contains filtered or unexported fields
}
ContainsValidator tests whether a container holds a specific string.
func (*ContainsValidator) FailureMsg ¶
func (v *ContainsValidator) FailureMsg() string
FailureMsg returns a string with a readable message about the validation failure.
func (*ContainsValidator) Type ¶
func (v *ContainsValidator) Type() string
Type returns the constraint name (contains).
func (*ContainsValidator) Validate ¶
func (v *ContainsValidator) Validate(val interface{}, params []string) bool
Validate tests for a existence of a string within another string, Array, Slice or Map (keys). Returns true if val is a String, Array, Slice or Map containing the string specified in params. Contains is case-sensitive. Validate panics if val is not a String, Array, Slice or Map.
type Context ¶
type Context struct { Request *http.Request Writer http.ResponseWriter RouteParams map[string]string Reader io.ReadCloser Identity Identity X interface{} // contains filtered or unexported fields }
Context is the request context. Context encapsulates the underlying Req and Writer, but exposes them if required. It provides many helper methods which are designed to keep your handler code clean and free from boiler code.
func (*Context) Authenticated ¶
Authenticated returns true if a request user has been authenticated. Authentication should be performed in a pre-hook, assigning a valid Identity to the Context if authentication succeeds. This method simply examines whether the Context has a valid Identity.
func (*Context) Bind ¶
Bind populates the supplied model with data from the request. This is performed in stages. initially, any requestbody content is deserialized.
TODO: Following is not yet implemented:
Route parameters are used next to populate any unset members. Finally, query parameters are used to populate any remaining unset members.
This method is under review - currently Binding only uses deserialized request body content.
func (*Context) Error ¶
Error sends the specified message and HTTP status code as a response. Request handlers should cease execution after calling this method.
func (*Context) GetEncoder ¶
GetEncoder returns an Encoder suitable for serializing data in a response. The Encoder is selected based on the request Accept header (or default media type if no Accept header supplied). If successful, the an encoder and content-type are returned and a nil error. Success is determined by a nil error. The returned encoder will have been pre-injected with an io.Writer, so the Encode method can be called directly, passing the data to be encoded as the only parameter.
func (*Context) Redirect ¶
Redirect sends a redirect response using the specified URL and HTTP status. Request handlers should cease execution after calling this method. TODO: Not yet implemented
func (*Context) RespondWith ¶
RespondWith is a generic method for producing a simple response. It takes a single parameter whose type will determine the action.
Strings will be used for the response content. Integers will be used for the response status code. Any other type is deemed to be a model which will be serialized.
The serialization mechanism for the model will depend on the request Accept header, the encoding DefaultMediaType and whether the WithContentType method has been used. See the Response struct for more details. This method returns the Response object and can be chained.
type ContextHandlerFunc ¶
type ContextHandlerFunc func(*Context)
ContextHandlerFunc type is an adapter to allow the use of ordinary functions as HTTP handlers. It is similar to the standard library's http.HandlerFunc in that if f is a function with the appropriate signature, ContextHandlerFunc(f) is a Handler object that calls f.
func (ContextHandlerFunc) ServeHTTP ¶
func (f ContextHandlerFunc) ServeHTTP(c *Context)
ServeHTTP calls f(c).
type Decoder ¶
type Decoder interface {
Decode(v interface{}) error
}
Decoder is the interface that wraps the basic Decode method. Decode is used for de-serializing request data.
type DecoderFunc ¶
DecoderFunc is a function that returns a Decoder pre-injected with an io.Reader
type DigitsValidator ¶
type DigitsValidator struct{}
DigitsValidator tests for a sequence of digits.
func (*DigitsValidator) FailureMsg ¶
func (v *DigitsValidator) FailureMsg() string
FailureMsg returns a string with a readable message about the validation failure.
func (*DigitsValidator) Type ¶
func (v *DigitsValidator) Type() string
Type returns the constraint name (digits).
func (*DigitsValidator) Validate ¶
func (v *DigitsValidator) Validate(val interface{}, params []string) bool
Validate tests for digit values. Returns true if val is a string containing only digits 0-9. Validate panics if val is not a string.
type EmailValidator ¶
type EmailValidator struct{}
EmailValidator tests for a valid email address
func (*EmailValidator) FailureMsg ¶
func (v *EmailValidator) FailureMsg() string
FailureMsg returns a string with a readable message about the validation failure.
func (*EmailValidator) Type ¶
func (v *EmailValidator) Type() string
Type returns the constraint name (email).
func (*EmailValidator) Validate ¶
func (v *EmailValidator) Validate(val interface{}, params []string) bool
Validate tests for an email address. Returns true if val is an email address. Validate panics if val is not a string.
type EmptyValidator ¶
type EmptyValidator struct{}
EmptyValidator is the default validator used to validate parameters where no constraint has been stipulated. It returns true in all cases
func (*EmptyValidator) FailureMsg ¶
func (v *EmptyValidator) FailureMsg() string
FailureMsg returns a string with a readable message about the validation failure. As this validator never fails, this method just returns an empty string.
func (*EmptyValidator) Type ¶
func (v *EmptyValidator) Type() string
Type returns the constraint name. This is an empty string to ensure this validator is selected when no constraint has been specified in the route pattern parameter.
func (*EmptyValidator) Validate ¶
func (v *EmptyValidator) Validate(val interface{}, args []string) bool
Validate returns true in all cases. This is the default validator.
type Encoder ¶
type Encoder interface {
Encode(v interface{}) error
}
Encoder is the interface that wraps the basic Encode method. Encode is used for serializing response data.
type EncoderEngine ¶
type EncoderEngine interface { GetDecoder(r io.Reader, ct string) (Decoder, error) GetEncoder(w io.Writer, ct string) (Encoder, error) DefaultMediaType() string SetDefaultMediaType(mt string) AddEncoderFunc(ct string, fn EncoderFunc) error AddDecoderFunc(ct string, fn DecoderFunc) error }
EncoderEngine is the interface for the encoder/decoder management.
type EncoderFunc ¶
EncoderFunc is a function that returns an Encoder pre-injected with an io.Writer
type Hex32Validator ¶
type Hex32Validator struct{}
Hex32Validator tests for 32 bit hex values.
func (*Hex32Validator) FailureMsg ¶
func (v *Hex32Validator) FailureMsg() string
FailureMsg returns a string with a readable message about the validation failure.
func (*Hex32Validator) Type ¶
func (v *Hex32Validator) Type() string
Type returns the constraint name (hex32).
func (*Hex32Validator) Validate ¶
func (v *Hex32Validator) Validate(val interface{}, params []string) bool
Validate tests for 32 bit hex values. Returns true if val is a hexadecimal string in the range -80000000 to 7FFFFFFF. The test is not case sensitive, i.e. 3ef42bc7 and 3EF42BC7 will both return true. Validate panics if val is not a string.
type Hex64Validator ¶
type Hex64Validator struct{}
Hex64Validator tests for 64 bit hex values.
func (*Hex64Validator) FailureMsg ¶
func (v *Hex64Validator) FailureMsg() string
FailureMsg returns a string with a readable message about the validation failure.
func (*Hex64Validator) Type ¶
func (v *Hex64Validator) Type() string
Type returns the constraint name (hex64).
func (*Hex64Validator) Validate ¶
func (v *Hex64Validator) Validate(val interface{}, params []string) bool
Validate tests for 64 bit hex values. Returns true if val is a hexadecimal string in the range -8000000000000000 to 7FFFFFFFFFFFFFFF. The test is not case sensitive, i.e. 3ef42bc7 and 3EF42BC7 will both return true. Validate panics if val is not a string.
type HexValidator ¶
type HexValidator struct{}
HexValidator tests for a sequence of hexadecimal characters.
func (*HexValidator) FailureMsg ¶
func (v *HexValidator) FailureMsg() string
FailureMsg returns a string with a readable message about the validation failure.
func (*HexValidator) Type ¶
func (v *HexValidator) Type() string
Type returns the constraint name (hex).
func (*HexValidator) Validate ¶
func (v *HexValidator) Validate(val interface{}, params []string) bool
Validate tests for hex values. Returns true if if val is a string containing only hex characters, (i.e. 0-9, a-e, A-F). Validate panics if val is not a string.
type Identity ¶
Identity is the interface used to hold information of the user making the request. Implementations of Identity are should to created and populated in a pre-hook.
type InSetValidator ¶
type InSetValidator struct {
// contains filtered or unexported fields
}
InSetValidator tests a value is in a set.
func (*InSetValidator) FailureMsg ¶
func (v *InSetValidator) FailureMsg() string
FailureMsg returns a string with a readable message about the validation failure.
func (*InSetValidator) Type ¶
func (v *InSetValidator) Type() string
Type returns the constraint name (inset).
func (*InSetValidator) Validate ¶
func (v *InSetValidator) Validate(val interface{}, params []string) bool
Validate tests for a value within a set of values. Returns true if val is a string or int within the set specified in params. Validate panics if val is not a string or int.
type Int32Validator ¶
type Int32Validator struct{}
Int32Validator tests for 32 bit integer values.
func (*Int32Validator) FailureMsg ¶
func (v *Int32Validator) FailureMsg() string
FailureMsg returns a string with a readable message about the validation failure.
func (*Int32Validator) Type ¶
func (v *Int32Validator) Type() string
Type returns the constraint name (int32).
func (*Int32Validator) Validate ¶
func (v *Int32Validator) Validate(val interface{}, params []string) bool
Validate tests for 32 bit integer values. Returns true if val is a string containing an integer in the range -2147483648 to 2147483647 Validate panics if val is not a string.
type Int64Validator ¶
type Int64Validator struct{}
Int64Validator tests for 64 bit integer values.
func (*Int64Validator) FailureMsg ¶
func (v *Int64Validator) FailureMsg() string
FailureMsg returns a string with a readable message about the validation failure.
func (*Int64Validator) Type ¶
func (v *Int64Validator) Type() string
Type returns the constraint name (int64).
func (*Int64Validator) Validate ¶
func (v *Int64Validator) Validate(val interface{}, params []string) bool
Validate tests for 64 bit integer values. Returns true if val is a string containing an integer in the range -9223372036854775808 to 9223372036854775807 Validate panics if val is not a string.
type LenMaxValidator ¶
type LenMaxValidator struct {
// contains filtered or unexported fields
}
LenMaxValidator tests for a maximum length of String, Array, Slice or Map.
func (*LenMaxValidator) FailureMsg ¶
func (v *LenMaxValidator) FailureMsg() string
FailureMsg returns a string with a readable message about the validation failure.
func (*LenMaxValidator) Type ¶
func (v *LenMaxValidator) Type() string
Type returns the constraint name (lenmax).
func (*LenMaxValidator) Validate ¶
func (v *LenMaxValidator) Validate(val interface{}, params []string) bool
Validate tests for a maximum length. Returns true if length of val is lower or equal to the value specified in params. Validate panics if val is not a String, Array, Slice or Map, or if supplied params argument is not an integer.
type LenMinValidator ¶
type LenMinValidator struct {
// contains filtered or unexported fields
}
LenMinValidator tests for a minimim length of String, Array, Slice or Map.
func (*LenMinValidator) FailureMsg ¶
func (v *LenMinValidator) FailureMsg() string
FailureMsg returns a string with a readable message about the validation failure.
func (*LenMinValidator) Type ¶
func (v *LenMinValidator) Type() string
Type returns the constraint name (lenmin).
func (*LenMinValidator) Validate ¶
func (v *LenMinValidator) Validate(val interface{}, params []string) bool
Validate tests for a minimim length. Returns true if length of val is greater or equal to the value specified in params. Validate panics if val is not a String, Array, Slice or Map, or if supplied params argument is not an integer.
type LenRangeValidator ¶
type LenRangeValidator struct {
// contains filtered or unexported fields
}
LenRangeValidator tests for length of String, Array, Slice or Map, in a given range.
func (*LenRangeValidator) FailureMsg ¶
func (v *LenRangeValidator) FailureMsg() string
FailureMsg returns a string with a readable message about the validation failure.
func (*LenRangeValidator) Type ¶
func (v *LenRangeValidator) Type() string
Type returns the constraint name (lenrange).
func (*LenRangeValidator) Validate ¶
func (v *LenRangeValidator) Validate(val interface{}, params []string) bool
Validate tests for a length in a given range. Returns true if length of val is between the lower and upper limits specified in params. Validate panics if val is not a String, Array, Slice or Map, or if supplied params arguments are not an integer.
type MaxValidator ¶
type MaxValidator struct {
// contains filtered or unexported fields
}
MaxValidator tests for a maxumum numeric value.
func (*MaxValidator) FailureMsg ¶
func (v *MaxValidator) FailureMsg() string
FailureMsg returns a string with a readable message about the validation failure.
func (*MaxValidator) Type ¶
func (v *MaxValidator) Type() string
Type returns the constraint name (max).
func (*MaxValidator) Validate ¶
func (v *MaxValidator) Validate(val interface{}, params []string) bool
Validate tests for a maximum numerical value. Returns true if val is a number lower or equal to the value specified in params. Validate panics if val is not a number or supplied params argument is not a number.
type MinValidator ¶
type MinValidator struct {
// contains filtered or unexported fields
}
MinValidator tests for a minumum numeric value.
func (*MinValidator) FailureMsg ¶
func (v *MinValidator) FailureMsg() string
FailureMsg returns a string with a readable message about the validation failure.
func (*MinValidator) Type ¶
func (v *MinValidator) Type() string
Type returns the constraint name (min).
func (*MinValidator) Validate ¶
func (v *MinValidator) Validate(val interface{}, params []string) bool
Validate tests for a minimum numerical value. Returns true if val is a number greater or equal to the value specified in params. Validate panics if val is not a number or supplied params argument is not a number.
type ModelValidator ¶
type ModelValidator interface { AddCustomValidator(m interface{}, fn ValidateFunc) Validate(m interface{}) (map[string][]ValidationFailure, bool) }
ModelValidator is the interface describing a model validator.
type NotEmptyOrWhitespaceValidator ¶
type NotEmptyOrWhitespaceValidator struct{}
NotEmptyOrWhitespaceValidator tests that a string is not empty and does not comprise only whitespace characters.
func (*NotEmptyOrWhitespaceValidator) FailureMsg ¶
func (v *NotEmptyOrWhitespaceValidator) FailureMsg() string
FailureMsg returns a string with a readable message about the validation failure.
func (*NotEmptyOrWhitespaceValidator) Type ¶
func (v *NotEmptyOrWhitespaceValidator) Type() string
Type returns the constraint name (notemptyorwhitespace).
func (*NotEmptyOrWhitespaceValidator) Validate ¶
func (v *NotEmptyOrWhitespaceValidator) Validate(val interface{}, params []string) bool
Validate tests for whitespace or empty string. Returns true if val is not an empty string or a string containing only whitespace characters. Validate panics if val is not a string.
type NotEmptyValidator ¶
type NotEmptyValidator struct{}
NotEmptyValidator tests for an empty String, Array, Slice or Map.
func (*NotEmptyValidator) FailureMsg ¶
func (v *NotEmptyValidator) FailureMsg() string
FailureMsg returns a string with a readable message about the validation failure.
func (*NotEmptyValidator) Type ¶
func (v *NotEmptyValidator) Type() string
Type returns the constraint name (notempty).
func (*NotEmptyValidator) Validate ¶
func (v *NotEmptyValidator) Validate(val interface{}, params []string) bool
Validate tests for an empty String, Array, Slice or Map. Returns true if val is String, Array, Slice or Map with elements. Equivlent to (and shorthand for) minlen(1). Validate panics if val is not a String, Array, Slice or Map.
type NotNilValidator ¶
type NotNilValidator struct{}
NotNilValidator tests for an uninitialized map or slice, or nil pointer.
func (*NotNilValidator) FailureMsg ¶
func (v *NotNilValidator) FailureMsg() string
FailureMsg returns a string with a readable message about the validation failure.
func (*NotNilValidator) Type ¶
func (v *NotNilValidator) Type() string
Type returns the constraint name (notnil).
func (*NotNilValidator) Validate ¶
func (v *NotNilValidator) Validate(val interface{}, params []string) bool
Validate tests for an uninitialized map or slice, or nil pointer. Returns true if val is an initialized map or slice, or non-nil pointer. Validate panics if val is not a map, slice or pointer.
type NotWhitespaceValidator ¶
type NotWhitespaceValidator struct{}
NotWhitespaceValidator tests that a string does not comprise only whitespace characters.
func (*NotWhitespaceValidator) FailureMsg ¶
func (v *NotWhitespaceValidator) FailureMsg() string
FailureMsg returns a string with a readable message about the validation failure.
func (*NotWhitespaceValidator) Type ¶
func (v *NotWhitespaceValidator) Type() string
Type returns the constraint name (notwhitespace).
func (*NotWhitespaceValidator) Validate ¶
func (v *NotWhitespaceValidator) Validate(val interface{}, params []string) bool
Validate tests for whitespace. Returns true if val is not a string containing only whitespace characters. Validate panics if val is not a string.
type NotZeroValidator ¶
type NotZeroValidator struct{}
NotZeroValidator tests for a value of zero.
func (*NotZeroValidator) FailureMsg ¶
func (v *NotZeroValidator) FailureMsg() string
FailureMsg returns a string with a readable message about the validation failure.
func (*NotZeroValidator) Type ¶
func (v *NotZeroValidator) Type() string
Type returns the constraint name (notzero).
func (*NotZeroValidator) Validate ¶
func (v *NotZeroValidator) Validate(val interface{}, params []string) bool
Validate tests for a numerical value of zero. Returns true if val is a number not equal to zero. Validate panics if val is not a number.
type PhoneValidator ¶
type PhoneValidator struct{}
PhoneValidator tests for a telephone number.
func (*PhoneValidator) FailureMsg ¶
func (v *PhoneValidator) FailureMsg() string
FailureMsg returns a string with a readable message about the validation failure.
func (*PhoneValidator) Type ¶
func (v *PhoneValidator) Type() string
Type returns the constraint name (phone).
func (*PhoneValidator) Validate ¶
func (v *PhoneValidator) Validate(val interface{}, params []string) bool
Validate tests for phone number. Returns true if val is a string containing only characters found in a telephone number. e.g. +44 1752 123456, (1752) 123456 or 01752 123456 Validate panics if val is not a string.
type PrefixValidator ¶
type PrefixValidator struct {
// contains filtered or unexported fields
}
PrefixValidator tests for a specified prefix.
func (*PrefixValidator) FailureMsg ¶
func (v *PrefixValidator) FailureMsg() string
FailureMsg returns a string with a readable message about the validation failure.
func (*PrefixValidator) Type ¶
func (v *PrefixValidator) Type() string
Type returns the constraint name (prefix).
func (*PrefixValidator) Validate ¶
func (v *PrefixValidator) Validate(val interface{}, params []string) bool
Validate tests for a prefix. Returns true if val is a string starting with the prefix specified in params. Validate panics if val is not a string.
type RangeValidator ¶
type RangeValidator struct {
// contains filtered or unexported fields
}
RangeValidator tests for a numerical value in a given range.
func (*RangeValidator) FailureMsg ¶
func (v *RangeValidator) FailureMsg() string
FailureMsg returns a string with a readable message about the validation failure.
func (*RangeValidator) Type ¶
func (v *RangeValidator) Type() string
Type returns the constraint name (range).
func (*RangeValidator) Validate ¶
func (v *RangeValidator) Validate(val interface{}, params []string) bool
Validate tests for a numerical value in a given range. Returns true if val is a number between the lower and upper limits specified in params. Example: range(2,4) - returns true if input is between 2 and 4 (inclusive). RangeValidator accepts all numeric types, e.g. range(3.123, 23456.89). Validate panics if val is not a number or supplied params arguments are not a numbers.
type Registerer ¶
type Registerer interface {
Register(r *Router)
}
Registerer is the interface that handler function modules need to implement.
type RequestLog ¶
type RequestLog struct { // Start is the time the request was received Start time.Time Finish time.Time // Host is the host on which the requested resource resides. // Format is "host:port" although port is omitted for standard // ports. // Example: www.somedomain.com Host string // AccessRequest is a concatenation of request information, in the // format: METHOD Path&Query protocol // // e.g. GET /somepath/more/thing.gif HTTP/1.1 AccessRequest string // Status is the response status code Status int // BytesOut is the number of bytes returned by the response BytesOut int // Duration is the time taken to process the request. Duration time.Duration // UserAgent is the client's user agent string (if provided) UserAgent string // RemoteAddr is the network address that sent the request. // Format is "IP:port" RemoteAddr string // Referer is the referring URL (if provided). // Referer is misspelled deliberately to match HTTP specification. Referer string // UserID returns the UserID of the authenticated user making the // request. Returns "-" if the request user has not been authenticated. UserID string // Method is the HTTP request method. Method string // URI is the path and query of the request URI. URI string // Protocol is the HTTP Protocol used for the request. Protocol string // contains filtered or unexported fields }
RequestLog is the structure used to record data about a request (and response). In addition to information extracted from the request object, this struct holds details about the duration, status and amount of data returned.
func NewRequestLog ¶
func NewRequestLog(req *http.Request) *RequestLog
NewRequestLog returns an initialized *RequestLog populated with information extracted from req.
func (*RequestLog) CombinedFormat ¶
func (r *RequestLog) CombinedFormat() string
CombinedFormat returns request data as a string in Combined Log Format. Combined Log Format is similar to Common Log Format, with the addition of the Referer and UserAgent.
func (*RequestLog) CommonFormat ¶
func (r *RequestLog) CommonFormat() string
CommonFormat returns request data as a string in W3C Common Log Format. (https://en.wikipedia.org/wiki/Common_Log_Format)
func (*RequestLog) Context ¶
func (r *RequestLog) Context() interface{}
Context returns the user defined X property of the mango context.
func (*RequestLog) Header ¶
func (r *RequestLog) Header(key string) string
Header returns the request header value for the specified key. Returns an empty string if no matching header is found.
func (*RequestLog) Identity ¶
func (r *RequestLog) Identity() Identity
Identity returns the identity of the authenticated user. Identity is a property of the mango context and must be set in the consuming application (e.g. using a custom authenticaion hook).
type RequestLogFunc ¶
type RequestLogFunc func(*RequestLog)
RequestLogFunc is the signature for implementing router RequestLogger
type Resource ¶
type Resource struct { Handlers map[string]ContextHandlerFunc RouteParams map[string]string CORSConfig *CORSConfig }
Resource is a container holding the Handler functions for the various HTTP methods, a RouteParams map of values obtained from the request path and a CORS configuration. The CORS config may be nil.
type Response ¶
type Response struct {
// contains filtered or unexported fields
}
Response is an object used to facilitate building a response.
func (*Response) WithContentType ¶
WithContentType sets the Content-Type header of the response. WithContentType overrides the default media type for this individual response. If the response contains a model and the Accept request header is missing, empty or equal to "*/*", then the model will be encoded with type ct. This method returns the Response object and can be chained.
func (*Response) WithHeader ¶
WithHeader adds a header to the response. This method returns the Response object and can be chained.
func (*Response) WithModel ¶
WithModel sets the Model that will be serialized for the response. The serialization mechanism will depend on the request Accept header, the encoding DefaultMediaType and whether the WithContentType method has been used. If the Accept request header is missing, empty or equal to "*/*", then the model will be encoded with the default media type. If required, the default media type can be overridden for the individual response using WithContentType. This method returns the Response object and can be chained.
func (*Response) WithStatus ¶
WithStatus sets the HTTP status code of the response. This method returns the Response object and can be chained.
type ResponseWriter ¶
type ResponseWriter struct {
// contains filtered or unexported fields
}
ResponseWriter implements the http.ResponseWriter interface and wraps the ResponseWriter provided to the ServeHTTP method. It's primary purpose is to collect data on the information written to provide more informative logging, but is used also for response compression.
func NewResponseWriter ¶
func NewResponseWriter(w http.ResponseWriter, acceptedEncoding string, compMinLen int) *ResponseWriter
NewResponseWriter returns an initialized instance of a ResponseWriter. If compMinLen is set above zero, then responses may be compressed if:
a) the body is longer than compMinLen bytes, b) a suitable format has been requested in the accept-encoding header
(currently this must be gzip or deflate),
c) headers have not already been sent using the WriteHeader method
func (*ResponseWriter) Header ¶
func (r *ResponseWriter) Header() http.Header
Header returns the header map that will be sent by WriteHeader. See http.ResponseWriter interface for more information.
func (*ResponseWriter) Write ¶
func (r *ResponseWriter) Write(b []byte) (int, error)
Write writes the data to the underlying http.ResponseWriter connection as part of an HTTP reply. The cumulative number of bytes is recorded to provide more informative logging. See http.ResponseWriter interface for more information.
func (*ResponseWriter) WriteHeader ¶
func (r *ResponseWriter) WriteHeader(status int)
WriteHeader sends an HTTP response header with status code to the underlying http.ResponseWriter. Status code is recorded to provide more informative logging. See http.ResponseWriter interface for more information.
type Router ¶
type Router struct { ValidationHandler EncoderEngine RequestLogger RequestLogFunc ErrorLogger func(error) AutoPopulateOptionsAllow bool CompMinLength int // contains filtered or unexported fields }
Router is the main mango object. Router implements the standard library http.Handler interface, so it can be used in the call to http.ListenAndServe method. New Router objects should be created using the NewRouter method rather than creating a new uninitialised instance. TODO: Add more info here.
func NewRouter ¶
func NewRouter() *Router
NewRouter returns a pointer to a new Router instance. The Router will be initialised with a new EncoderEngine, Validation handlers for route parameters and models, and route handling functionality.
func (*Router) AddCORS ¶
func (r *Router) AddCORS(pattern string, config CORSConfig)
AddCORS sets the CORS configuration that will be used for the resource matching the pattern, by merging the supplied config with any globalCORSConfig. SetGlobalCORS MUST be called before this method! AddCORS will panic if GlobalCORS is nil.
func (*Router) AddModelValidator ¶
func (r *Router) AddModelValidator(m interface{}, fn ValidateFunc)
AddModelValidator adds a custom model validator to the collection.
func (*Router) AddPostHook ¶
func (r *Router) AddPostHook(hook ContextHandlerFunc)
AddPostHook adds a ContextHandlerFunc that will be called after a handler function has been called. PostHooks can be used to perform cleanup tasks etc., but unlike PreHooks, they cannot alter a response. Note: PostHooks are executed in the order they are added.
func (*Router) AddPreHook ¶
func (r *Router) AddPreHook(hook ContextHandlerFunc)
AddPreHook adds a ContextHandlerFunc that will be called before any handler function is called. They can be used to sanitize requests, authenticate users, adding CORS handling etc. and can respond directly, preventing any handler from executing if required. Note: PreHooks are executed in the order they are added.
func (*Router) Delete ¶
func (r *Router) Delete(pattern string, handlerFunc ContextHandlerFunc)
Delete registers a new handlerFunc that will be called when HTTP DELETE requests are made to URLs with paths that match pattern. If a DELETE handlerFunc already exists for pattern, Delete panics.
func (*Router) Get ¶
func (r *Router) Get(pattern string, handlerFunc ContextHandlerFunc)
Get registers a new handlerFunc that will be called when HTTP GET requests are made to URLs with paths that match pattern. If a GET handlerFunc already exists for pattern, Get panics.
func (*Router) Head ¶
func (r *Router) Head(pattern string, handlerFunc ContextHandlerFunc)
Head registers a new handlerFunc that will be called when HTTP HEAD requests are made to URLs with paths that match pattern. If a HEAD handlerFunc already exists for pattern, Head panics.
func (*Router) Options ¶
func (r *Router) Options(pattern string, handlerFunc ContextHandlerFunc)
Options registers a new handlerFunc that will be called when HTTP OPTIONS requests are made to URLs with paths that match pattern. If a OPTIONS handlerFunc already exists for pattern, Options panics.
func (*Router) Patch ¶
func (r *Router) Patch(pattern string, handlerFunc ContextHandlerFunc)
Patch registers a new handlerFunc that will be called when HTTP PATCH requests are made to URLs with paths that match pattern. If a PATCH handlerFunc already exists for pattern, Patch panics.
func (*Router) Post ¶
func (r *Router) Post(pattern string, handlerFunc ContextHandlerFunc)
Post registers a new handlerFunc that will be called when HTTP POST requests are made to URLs with paths that match pattern. If a POST handlerFunc already exists for pattern, Post panics.
func (*Router) Put ¶
func (r *Router) Put(pattern string, handlerFunc ContextHandlerFunc)
Put registers a new handlerFunc that will be called when HTTP PUT requests are made to URLs with paths that match pattern. If a PUT handlerFunc already exists for pattern, Put panics.
func (*Router) RegisterModules ¶
func (r *Router) RegisterModules(modules []Registerer)
RegisterModules registers the route handler functions in each of the modules. If a specific pattern-method handlerFunc already exists, RegisterModules panics.
func (*Router) ServeHTTP ¶
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)
ServeHTTP dispatches the request to the handler whose pattern matches the request URL.
func (*Router) SetCORS ¶
func (r *Router) SetCORS(pattern string, config CORSConfig)
SetCORS sets the CORS configuration that will be used for the resource matching the pattern. These settings override any global settings.
func (*Router) SetGlobalCORS ¶
func (r *Router) SetGlobalCORS(config CORSConfig)
SetGlobalCORS sets the CORS configuration that will be used for a resource if it has no CORS configuration of its own. If the resource has no CORSConfig and tree.GlobalCORSConfig is nil then CORS request are treated like any other.
type SentenceValidator ¶
type SentenceValidator struct{}
SentenceValidator tests for a sequence containing only characters normally found in a sentence.
func (*SentenceValidator) FailureMsg ¶
func (v *SentenceValidator) FailureMsg() string
FailureMsg returns a string with a readable message about the validation failure.
func (*SentenceValidator) Type ¶
func (v *SentenceValidator) Type() string
Type returns the constraint name (sentence).
func (*SentenceValidator) Validate ¶
func (v *SentenceValidator) Validate(val interface{}, params []string) bool
Validate tests for characters normally found in a sentence. Returns true if val is a string containing only characters in the ranges a-z, A-Z or 0-9, plus spaces and punctuation characters ,.:;!? single and double quotes, braces and hyphens. Note that underscores are not included in the permissble set. Validate panics if val is not a string.
type SuffixValidator ¶
type SuffixValidator struct {
// contains filtered or unexported fields
}
SuffixValidator tests for a specified suffix.
func (*SuffixValidator) FailureMsg ¶
func (v *SuffixValidator) FailureMsg() string
FailureMsg returns a string with a readable message about the validation failure.
func (*SuffixValidator) Type ¶
func (v *SuffixValidator) Type() string
Type returns the constraint name (suffix).
func (*SuffixValidator) Validate ¶
func (v *SuffixValidator) Validate(val interface{}, params []string) bool
Validate tests for a suffix. Returns true if val is a string ending with the suffix specified in params. Validate panics if val is not a string.
type UUIDValidator ¶
type UUIDValidator struct{}
UUIDValidator tests for UUIDs.
func (*UUIDValidator) FailureMsg ¶
func (v *UUIDValidator) FailureMsg() string
FailureMsg returns a string with a readable message about the validation failure.
func (*UUIDValidator) Type ¶
func (v *UUIDValidator) Type() string
Type returns the constraint name (uuid).
func (*UUIDValidator) Validate ¶
func (v *UUIDValidator) Validate(val interface{}, params []string) bool
Validate tests for UUID values. Returns true if val is a string in one of the following formats:
xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx) xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} (xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx) XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} (XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX) XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX {XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX} (XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX)
where X and x represent upper and lowercase hexadecimal values respectively.
Valid UUID examples:
{58D5E212-165B-4CA0-909B-C86B9CEE0111} {58d5e212-165b-4ca0-909b-c86b9cee0111} 58D5E212165B4CA0909BC86B9CEE0111
Validate panics if val is not a string.
type UnsupportedMediaTypeError ¶
type UnsupportedMediaTypeError struct {
// contains filtered or unexported fields
}
UnsupportedMediaTypeError means that the request payload was not in an acceptable format. This error occurs if the header value for either 'content-type' or 'content-encoding' is not recognised.
func (UnsupportedMediaTypeError) Error ¶
func (e UnsupportedMediaTypeError) Error() string
type ValidateFunc ¶
type ValidateFunc func(m interface{}) (map[string][]ValidationFailure, bool)
ValidateFunc is the signature for implementing custom model validators.
type ValidationFailure ¶
ValidationFailure holds details about a validation failure. Code will contain the validator type and Message a user friendly description of the reason for the failure.
type ValidationHandler ¶
type ValidationHandler interface { AddValidator(v Validator) AddValidators(validators []Validator) IsValid(val interface{}, constraints string) ([]ValidationFailure, bool) ParseConstraints(constraints string) map[string][]string }
ValidationHandler is the interface for a collection of Validators. The IsValid method can be used to validate a model property or checking a route parameter value against its constraint. New validators can be added individually using AddValidator or as a collection using AddValidators.
type Validator ¶
type Validator interface { // Validate tests if val matches the validation rules. The validation test // may involve constraint specific args. Validate(val interface{}, args []string) bool // Type returns the constraint name used in routing patterns. // ValidationHandler will use this to locate the correct validator. Type() string // FailureMsg returns a string with a readable message about the validation failure. FailureMsg() string }
Validator is the interface that wraps the basic Validate method. Validators are used to validate models in addition to sections of a URL path which match the pattern of an entry in the routing tree.