routex

package module
v1.2.5 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2022 License: Apache-2.0 Imports: 12 Imported by: 1

README

RouteX

RouteX is a Django-like HTTP Router for Golang and adds a JSON validator for data sets.

RouteX can assist with handling RESTful request processing. Take a look at the "examples/example1.go" file for a peek on how to set up a basic GET/POST/LIST model.

Documentation

Index

Constants

View Source
const (
	// ErrNoBody is an error returned when there is no content passed to an HTTP
	// request when it's required.
	ErrNoBody = errStr("missing HTTP body")
	// ErrNotExists is an error returned from any of the Content getter functions
	// when the value by the supplied name does not exist in the Content map.
	ErrNotExists = errStr("value does not exist")
	// ErrInvalidType is an error returned from any of the Content getter functions
	// when the value by the supplied name is not the requested value.
	ErrInvalidType = errStr("incorrect value type")
)
View Source
const (
	// ErrInvalidPath is returned from the 'Add*' functions when the path is empty.
	ErrInvalidPath = errStr("supplied path is invalid")
	// ErrInvalidRegexp is returned from the 'AddExp*' functions when the Regexp
	// expression is nil.
	ErrInvalidRegexp = errStr("cannot use a nil Regexp")
	// ErrInvalidHandler is returned from the 'Add*' functions when the Handler is
	// nil.
	ErrInvalidHandler = errStr("cannot use a nil Handler")
	// ErrInvalidMethod is an error returned when the HTTP method names provided
	// are empty.
	ErrInvalidMethod = errStr("supplied methods contains an empty method name")
)
View Source
const ErrEmptyValue = errStr("value is empty")

ErrEmptyValue is an error returned from number conversion functions when the string value is empty and does not represent a number.

Variables

This section is empty.

Functions

func JSON added in v1.0.2

func JSON(w http.ResponseWriter, c int, i any)

JSON will write the supplied interface to the ResponseWrite with the supplied status.

DO NOT expect the writer to be usage afterwards.

This function automatically sets the encoding to JSON.

Types

type Content

type Content map[string]any

Content is an alias of a JSON data payload sent to the server.

func (Content) Bool added in v1.0.1

func (c Content) Bool(s string) (bool, error)

Bool attempts to return the value with the provided name as a boolean value.

This function will return an 'ErrNotExists' error if the value by the specified name does not exist or 'ErrInvalidType' if the value does not represent a boolean type.

func (Content) BoolDefault added in v1.0.1

func (c Content) BoolDefault(s string, d bool) bool

BoolDefault attempts to return the value with the provided name as a boolean value.

This function will return the default value specified if the value does not exist or is not a boolean type.

func (Content) Bytes added in v1.2.2

func (c Content) Bytes(s string) ([]byte, error)

Bytes attempts to return the value with the provided name as a byte slice value that is represented by a Base64-encoded string.

This function will return an 'ErrNotExists' error if the value by the specified name does not exist or 'ErrInvalidType' if the value does not represent a bytes type.

This will attempt to decode the Base64 string and will return the encoding errors if they occur.

func (Content) BytesDefault added in v1.2.3

func (c Content) BytesDefault(s string, d []byte) []byte

BytesDefault to return the value with the provided name as a byte slice value that is represented by a Base64-encoded string.

This function will return the default value specified if the value does not exist or is not a bytes type.

This will attempt to decode the Base64 string and will return the default value if errors occur.

func (Content) BytesEmpty added in v1.2.4

func (c Content) BytesEmpty(s string) ([]byte, error)

BytesEmpty attempts to return the value with the provided name as a byte slice value that is represented by a Base64-encoded string.

This function will return an 'ErrInvalidType' if the value does not represent a bytes type. Empty or missing values will simply return none.

This function is different than the other 'Bytes' function as it allows for empty/missing byte slices but not invalid or improperly formatted ones.

This will attempt to decode the Base64 string and will return the encoding errors if they occur.

func (Content) Float added in v1.0.2

func (c Content) Float(s string) (float64, error)

Float attempts to return the value with the provided name as a floating point value.

This function will return an 'ErrNotExists' error if the value by the specified name does not exist or 'ErrInvalidType' if the value does not represent a float type.

func (Content) FloatDefault added in v1.0.2

func (c Content) FloatDefault(s string, d float64) float64

FloatDefault attempts to return the value with the provided name as a floating point value.

This function will return the default value specified if the value does not exist or is not a float type.

func (Content) Int added in v1.0.2

func (c Content) Int(s string) (int64, error)

Int attempts to return the value with the provided name as an integer value.

This function will return an 'ErrNotExists' error if the value by the specified name does not exist or 'ErrInvalidType' if the value does not represent an integer type.

func (Content) IntDefault added in v1.0.2

func (c Content) IntDefault(s string, d int64) int64

IntDefault attempts to return the value with the provided name as an integer value.

This function will return the default value specified if the value does not exist or is not an integer type.

func (Content) Object

func (c Content) Object(s string) (Content, error)

Object attempts to return the value with the provided name as a complex object value (wrapped as a Content alias).

This function will return an 'ErrNotExists' error if the value by the specified name does not exist or 'ErrInvalidType' if the value does not represent an object type.

func (Content) ObjectDefault added in v1.0.1

func (c Content) ObjectDefault(s string, d Content) Content

ObjectDefault attempts to return the value with the provided name as an object value (wrapped as a Content alias).

This function will return the default value specified if the value does not exist or is not an object type.

func (Content) Raw

func (c Content) Raw(s string) any

Raw returns the raw interface value with the supplied value name.

This function returns nil if the name does not exist. This is similar to directly calling the name in a map.

func (Content) String

func (c Content) String(s string) (string, error)

String attempts to return the value with the provided name as a string value.

This function will return an 'ErrNotExists' error if the value by the specified name does not exist or 'ErrInvalidType' if the value does not represent a string type.

func (Content) StringDefault added in v1.0.1

func (c Content) StringDefault(s, d string) string

StringDefault attempts to return the value with the provided name as a string value.

This function will return the default value specified if the value does not exist or is not a string type.

func (Content) Uint added in v1.0.2

func (c Content) Uint(s string) (uint64, error)

Uint attempts to return the value with the provided name as an unsigned integer value.

This function will return an 'ErrNotExists' error if the value by the specified name does not exist or 'ErrInvalidType' if the value does not represent an integer type.

func (Content) UintDefault added in v1.0.2

func (c Content) UintDefault(s string, d uint64) uint64

UintDefault attempts to return the value with the provided name as an unsigned integer value.

This function will return the default value specified if the value does not exist or is not an unsigned integer type.

type ConvertFunc added in v1.0.0

type ConvertFunc http.HandlerFunc

ConvertFunc is an alias for the standard 'http.HandlerFunc' that can be used for compatibility with any built-in interface support.

func (ConvertFunc) Handle added in v1.0.2

Handle allows this alias to fulfill the Handler interface.

type ErrorFunc added in v1.0.2

type ErrorFunc func(int, string, http.ResponseWriter, *Request)

ErrorFunc is an alias that can be used to use a function signature as a 'ErrorHandler' instead.

func (ErrorFunc) HandleError added in v1.0.2

func (f ErrorFunc) HandleError(c int, s string, w http.ResponseWriter, r *Request)

HandleError allows this alias to fulfill the ErrorHandler interface.

type ErrorHandler added in v1.0.0

type ErrorHandler interface {
	HandleError(int, string, http.ResponseWriter, *Request)
}

ErrorHandler is an interface that allows for handling any error returns to be reported to the client instead of using the default methods.

The 'HandleError' method will be called with an error status code, error message and the standard 'Handler' options (except the Context).

type Func added in v1.0.0

Func is an alias that can be used to use a function signature as a 'Handler' instead.

func (Func) Handle added in v1.0.0

func (f Func) Handle(x context.Context, w http.ResponseWriter, r *Request)

Handle allows this alias to fulfill the Handler interface.

type Handler

type Handler interface {
	Handle(context.Context, http.ResponseWriter, *Request)
}

Handler is a fork of the http.Handler interface. This interface supplies a base Context to be used and augments the supplied Request to have options for getting formatted JSON body content or getting the URL match groups.

func Convert added in v1.0.0

func Convert(h http.Handler) Handler

Convert is a wrapper for the standard 'http.Handler' that can be used for compatibility with any built-in interface to support RouteX functions.

func Marshal added in v1.0.0

func Marshal[T any](v Validator, h Marshaler[T]) Handler

Marshal will create a handler that will attempt to unmarshal a copy of the supplied interface object once successfully validated by the supplied validator.

An empty or 'new(obj)' variant of the requested data will work for this function.

func Wrap

func Wrap(v Validator, h Wrapper) Handler

Wrap will create a handler with the specified Validator that will check the content before passing control to the specified Handler.

type MarshalFunc

type MarshalFunc[T any] func(context.Context, http.ResponseWriter, *Request, T)

MarshalFunc is an alias that can be used to use a function signature as a 'Marshaler' instead.

func (MarshalFunc[T]) Handle added in v1.0.2

func (f MarshalFunc[T]) Handle(x context.Context, w http.ResponseWriter, r *Request, v T)

Handle allows this alias to fulfill the Marshaler interface.

type Marshaler

type Marshaler[T any] interface {
	Handle(context.Context, http.ResponseWriter, *Request, T)
}

Marshaler is an interface that can wrap a Handler to instead directly get the associated struct type from the Router instead. These can be created using the 'Marshal*' functions passed with a Validator.

type Middleware added in v1.0.2

type Middleware func(context.Context, http.ResponseWriter, *Request) bool

Middleware is a function alias that can be used to handle and work on a request before it is handled to the assigned Mux function (or default function).

Middlewares applied to Routes will be applied AFTER the global Mux Middleware.

The returned boolean can be used to interrupt the call stack before handling back control to implement features such as redirects or authentication.

type Mux

type Mux struct {
	Error, Error404    ErrorHandler
	Error405, Error500 ErrorHandler

	Default Handler

	Timeout time.Duration
	// contains filtered or unexported fields
}

Mux is a http Handler that can be used to handle connections based on Regex expression paths. Matching groups passed in the request URL values may be parsed out and passed to the resulting request.

This Handler supports a base context that can be used to signal closure to all running Handlers.

func New

func New() *Mux

New returns a new Mux instance.

func NewContext

func NewContext(x context.Context) *Mux

NewContext creates a new Mux and applies the supplied Context as the Mux base Context.

func (*Mux) Add added in v1.0.0

func (m *Mux) Add(path string, h Handler, methods ...string) (Route, error)

Add adds the Handler to the supplied regex expression path. Path values must be unique and don't have to contain regex expressions.

Regex match groups can be used to grab data out of the call and will be placed in the 'Values' Request map.

This function returns an error if a duplicate path exists or the regex expression is invalid.

This function will add a handler that will be considered the 'default' handler for the path and will be called unless a method-based Handler is also specified and that HTTP method is used.

func (*Mux) AddExp added in v1.0.0

func (m *Mux) AddExp(exp *regexp.Regexp, h Handler, methods ...string) (Route, error)

AddExp adds the Handler to the supplied regex expression. Path values must be unique and don't have to contain regex expressions.

Regex match groups can be used to grab data out of the call and will be placed in the 'Values' Request map.

This function returns an error if a duplicate path exists or the regex expression is invalid.

This function will add a handler that will be considered the 'default' handler for the path and will be called unless a method-based Handler is also specified and that HTTP method is used.

func (*Mux) Middleware added in v1.0.2

func (m *Mux) Middleware(w ...Middleware)

Middleware adds the supplied Middleware functions to the Mux. These are ran before control is passed until the Handler.

And empty function is considered a NOP.

func (*Mux) Must added in v1.0.0

func (m *Mux) Must(path string, h Handler, methods ...string) Route

Must adds the Handler to the supplied regex expression path. Path values must be unique and don't have to contain regex expressions.

Regex match groups can be used to grab data out of the call and will be placed in the 'Values' Request map.

This function panics if a duplicate path exists or the regex expression is invalid.

This function will add a handler that will be considered the 'default' handler for the path and will be called unless a method-based Handler is also specified and that HTTP method is used.

func (*Mux) MustExp added in v1.0.0

func (m *Mux) MustExp(exp *regexp.Regexp, h Handler, methods ...string) Route

MustExp adds the Handler to the supplied regex expression. Path values must be unique and don't have to contain regex expressions.

Regex match groups can be used to grab data out of the call and will be placed in the 'Values' Request map.

This function panics if a duplicate path exists or the regex expression is invalid.

This function will add a handler that will be considered the 'default' handler for the path and will be called unless a method-based Handler is also specified and that HTTP method is used.

func (*Mux) ServeHTTP

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

ServeHTTP allows RegexMux to fulfill the http.Handler interface.

func (*Mux) SetLog

func (m *Mux) SetLog(l logger)

SetLog will set the internal logger for the Mux instance. This can be used to debug any errors during runtime.

type Request

type Request struct {
	Mux *Mux

	Values values
	*http.Request
	// contains filtered or unexported fields
}

Request is an extension of the 'http.Request' struct.

This struct includes parsed values from the calling URL and offers some convenience functions for parsing the resulting data.

func (*Request) Content

func (r *Request) Content() (Content, error)

Content returns a content map based on the JSON body data passed in this request. This function returns 'ErrNoBody' if the Body is nil or empty.

Any JSON parsing errors will also be returned if they occur.

func (*Request) Context

func (r *Request) Context() context.Context

Context returns the request's context. The returned context is always non-nil.

This is a child of the base Handler context if supplied on Mux creation and can be canceled if the Handler is closed or any timeout is passed.

func (*Request) IsDelete

func (r *Request) IsDelete() bool

IsDelete returns true if this is a http DELETE request.

func (*Request) IsGet

func (r *Request) IsGet() bool

IsGet returns true if this is a http GET request.

func (*Request) IsHead

func (r *Request) IsHead() bool

IsHead returns true if this is a http HEAD request.

func (*Request) IsOptions

func (r *Request) IsOptions() bool

IsOptions returns true if this is a http OPTIONS request.

func (*Request) IsPatch added in v1.0.0

func (r *Request) IsPatch() bool

IsPatch returns true if this is a http PATCH request.

func (*Request) IsPost

func (r *Request) IsPost() bool

IsPost returns true if this is a http POST request.

func (*Request) IsPut

func (r *Request) IsPut() bool

IsPut returns true if this is a http PUT request.

func (*Request) Marshal

func (r *Request) Marshal(i any) error

Marshal will attempt to unmarshal the JSON body in the Request into the supplied interface.

This function returns 'ErrNoBody' if the Body is nil or empty.

Any JSON parsing errors will also be returned if they occur.

func (*Request) ValidateContent added in v1.0.2

func (r *Request) ValidateContent(v Validator) (Content, error)

ValidateContent returns a content map based on the JSON body data passed in this request.

This function allows for passing a Validator that can also validate the content before returning.

This will only validate if no JSON parsing errors are returned beforehand.

This function will return 'ErrNoBody' if no content was found or the request body is empty.

func (*Request) ValidateMarshal added in v1.0.2

func (r *Request) ValidateMarshal(v Validator, i any) error

ValidateMarshal is similar to the Marshal function but will validate the Request content with the specified Validator before returning.

This function returns 'ErrNoBody' if the Body is nil or empty.

Any JSON parsing errors will also be returned if they occur.

type Route added in v1.0.2

type Route interface {
	Middleware(m ...Middleware) Route
}

Route is an interface that allows for modification of an added HTTP route after being created.

One example function is adding route-specific middleware.

type Validator

type Validator interface {
	Validate(Content) error
}

Validator is an interface that allows for validation of Content data. By design, returning nil indicates that the supplied Content has passed all checks.

type WrapFunc

type WrapFunc func(context.Context, http.ResponseWriter, *Request, Content)

WrapFunc is an alias that can be used to use a function signature as a 'Wrapper' instead.

func (WrapFunc) Handle added in v1.0.2

func (f WrapFunc) Handle(x context.Context, w http.ResponseWriter, r *Request, c Content)

Handle allows this alias to fulfill the Wrapper interface.

type Wrapper

type Wrapper interface {
	Handle(context.Context, http.ResponseWriter, *Request, Content)
}

Wrapper is an interface that can wrap a Handler to instead directly get a Content object from the Router instead. These can be created using the 'Wrap*' functions passed with a Validator.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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