api

package
v0.1.5 Latest Latest
Warning

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

Go to latest
Published: Feb 13, 2022 License: MIT Imports: 35 Imported by: 0

Documentation

Overview

Package api is the hiro api helper library

Index

Constants

View Source
const (
	// PrincipalTypeUser should be returned if the principal is a user
	PrincipalTypeUser PrincipalType = "user"

	// PrincipalTypeApplication should be used if the principal is an application
	PrincipalTypeApplication PrincipalType = "application"

	// CredentialTypeBasic is http 401 Basic auth
	CredentialTypeBasic CredentialType = "Basic"

	// CredentialTypeBearer is HTTP Bearer token authentication
	CredentialTypeBearer CredentialType = "Bearer"

	// CredentialTypeAPIKey is used for other api key based authentications
	CredentialTypeAPIKey CredentialType = "ApiKey"
)

Variables

View Source
var (
	// ErrBadRequest should be returned for a bad request or invalid parameters
	ErrBadRequest = Errorf("bad request").WithStatus(http.StatusBadRequest)

	// ErrUnauthorized is returned when authentication has failed or is necessary
	ErrUnauthorized = Errorf("access denied").WithStatus(http.StatusUnauthorized)

	// ErrForbidden should be returned when an client is authenticated but not allowed
	ErrForbidden = Errorf("forbidden").WithStatus(http.StatusForbidden)

	// ErrNotFound is returned when an object is not found
	ErrNotFound = Errorf("not found").WithStatus(http.StatusNotFound)

	// ErrConflict should be returned when there is a conflict with resources
	ErrConflict = Errorf("conflict").WithStatus(http.StatusConflict)

	// ErrServerError should be returned for internal errors
	ErrServerError = Errorf("server error").WithStatus(http.StatusInternalServerError)

	// ErrAuthUnacceptable should be returned when an authorizer could not find data to decode
	ErrAuthUnacceptable = Errorf("no acceptable authorization data found").WithCode("unacceptable").WithStatus(http.StatusUnauthorized)

	// ErrNotImplemented is returned when a method is not implemented
	ErrNotImplemented = Errorf("operation is not implemented").WithCode("not_implemented").WithStatus(http.StatusNotImplemented)

	// ErrTimeout is returned when a request or operation times out
	ErrTimeout = Errorf("timeout").WithStatus(http.StatusRequestTimeout)
)

Functions

func AuthPrincipal

func AuthPrincipal(ctx context.Context, target interface{}) bool

AuthPrincipal the first auth principal that matches the target

func Context

func Context(ctx context.Context) interface{}

Context returns the request context object

func IsRequest

func IsRequest(ctx context.Context) bool

IsRequest returns true if the context is an http.Request

func Log

func Log(ctx context.Context) log.Interface

Log returns the logger

func Request

func Request(ctx context.Context) (*http.Request, http.ResponseWriter)

Request gets the reqest and response objects from the context

func RequestHost added in v0.1.1

func RequestHost(ctx context.Context) string

RequestHost returns the host from the current request

func RequestVersion

func RequestVersion(r *http.Request) string

RequestVersion returns the request version in the context

func RequirePrincipal

func RequirePrincipal(ctx context.Context, target interface{}, t ...PrincipalType)

RequirePrincipal panics with api.ErrUnauthorized on fail

func SessionManager

func SessionManager(ctx context.Context) *session.Manager

SessionManager returns the session store from the context

func Unauthorized

func Unauthorized(r *http.Request) (interface{}, error)

Unauthorized fails auth and can used by routes in the authorizer chain as an explicit deny, this is useful when there are authorizers with optional components

func Version

func Version(ctx context.Context) string

Version returns the request version from the context

func VersionMiddleware

func VersionMiddleware(v Versioner, header ...string) func(http.Handler) http.Handler

VersionMiddleware enforces versioning in the request path

func Write

func Write(w http.ResponseWriter, status int, payload interface{}, headers ...http.Header) error

Write writes the raw payload out expeting it to be bytes

func WriteJSON

func WriteJSON(w http.ResponseWriter, status int, payload interface{}, headers ...http.Header) error

WriteJSON writes json objects

func WriteXML

func WriteXML(w http.ResponseWriter, status int, payload interface{}, headers ...http.Header) error

WriteXML writes an object out as XML

Types

type AuthorizedRoute

type AuthorizedRoute interface {
	Route

	// RequireAuth returns the credential types this route requires
	RequireAuth() []CredentialType
}

AuthorizedRoute is used but authorizers to signify checking authorizers

type Authorizer

type Authorizer interface {
	Authorize(r *http.Request, rt Route) (Principal, error)
	CredentialType() CredentialType
}

Authorizer is the api authorizer interface

type AuthorizerFunc

type AuthorizerFunc func(r *http.Request, rt Route) (Principal, error)

AuthorizerFunc performs an authorization and returns a context or error on failure

type CachedRoute

type CachedRoute interface {
	Route

	Timeout() time.Duration
}

CachedRoute is a cached route interface

type Claims

type Claims interface {
	// Set sets a value in the claims
	Set(key string, value interface{})

	// Get gets a value in the claims
	Get(key string) interface{}

	// All should return all of the claims as a map
	All() map[string]interface{}
}

Claims is a basic claims interface

type CredentialType

type CredentialType string

CredentialType is the credential type

type Encoder

type Encoder interface {
	Encode(w io.Writer) error
}

Encoder is a response encoder

type ErrorResponse

type ErrorResponse interface {
	error
	Responder

	// Code returns the error code
	Code() string

	// Detail returns the detail
	Detail() []string

	// With error overrides the existing error if the status is greater, or sets the detail
	WithError(err error) ErrorResponse

	// WithMessage sets the message for the error
	WithMessage(format string, args ...interface{}) ErrorResponse

	// WithStatus sets the status code for the error
	WithStatus(status int) ErrorResponse

	// WithCode sets the error code for the response, the default is the http status
	WithCode(code string) ErrorResponse

	// WithDetail adds detail to the error
	WithDetail(detail ...interface{}) ErrorResponse
}

ErrorResponse is response with an error

func Error

func Error(err error) ErrorResponse

Error returns a new api error from the error

func Errorf

func Errorf(format string, args ...interface{}) ErrorResponse

Errorf returns a new api error from the string

type HandlerFunc

type HandlerFunc func(http.ResponseWriter, *http.Request) Responder

HandlerFunc is a generic handler server operations

type Option

type Option func(*Server)

Option provides the server options, these will override th defaults and any hiro instance values.

func WithAddr

func WithAddr(addr string) Option

WithAddr sets the listen address for the server

func WithBasepath

func WithBasepath(base string) Option

WithBasepath sets the router basepath for the api

func WithCORS

func WithCORS(origin ...string) Option

WithCORS sets the cors origin and enables cors on the router

func WithCache

func WithCache(ttl time.Duration) Option

WithCache enables content caching for the route

func WithListener

func WithListener(l net.Listener) Option

WithListener sets the net listener for the server

func WithLog

func WithLog(l log.Interface) Option

WithLog specifies a new logger

func WithRouter

func WithRouter(router *mux.Router) Option

WithRouter specifies the router to use

func WithServerName

func WithServerName(name string) Option

WithServerName specifies the server name

func WithTracing

func WithTracing(t bool) Option

WithTracing enables http tracing

func WithVersion

func WithVersion(v string) Option

WithVersion sets the specific version for the server

type Principal

type Principal interface {
	// Type should return the principal type
	Type() PrincipalType

	// CredentialType should return the credential type, i.e. Basic or Bearer
	CredentialType() CredentialType

	// Credentials should return the raw principal credentials
	Credentials() string

	// Returns the principal's authorization claims
	AuthClaims() Claims
}

Principal is an authorization principal

type PrincipalType

type PrincipalType string

PrincipalType defines a principal type

type Redirector added in v0.1.2

type Redirector struct {
	*Response
	// contains filtered or unexported fields
}

Redirector defines an api redirect

func Redirect

func Redirect(u *url.URL) *Redirector

Redirect will set the proper redirect headers and http.StatusFound

func (*Redirector) WithError added in v0.1.2

func (r *Redirector) WithError(err error) *Redirector

func (*Redirector) WithQuery added in v0.1.2

func (r *Redirector) WithQuery(vals *url.Values) *Redirector

type Responder

type Responder interface {
	// Status returns the http status
	Status() int

	// Payload is the payload
	Payload() interface{}

	// Write writes out the payload
	Write(w http.ResponseWriter) error
}

Responder is an api response interface

func RedirectErrIf added in v0.1.2

func RedirectErrIf(cond bool, u *url.URL, err error) Responder

RedirectErrIf does a conditional redirect with the error

func RedirectIf added in v0.1.2

func RedirectIf(cond bool, u *url.URL, val ...interface{}) Responder

RedirectIf does a conditional redirect

type Response

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

Response is the common response type

func NewResponse

func NewResponse(payload ...interface{}) *Response

NewResponse returns a response with defaults

func (*Response) Payload

func (r *Response) Payload() interface{}

Payload returns the payload

func (*Response) Status

func (r *Response) Status() int

Status returns the status

func (*Response) WithHeader

func (r *Response) WithHeader(key string, value string) *Response

WithHeader adds headers to the request

func (*Response) WithStatus

func (r *Response) WithStatus(status int) *Response

WithStatus sets the status

func (*Response) WithWriter

func (r *Response) WithWriter(w WriterFunc) *Response

WithWriter sets the writer

func (*Response) Write

func (r *Response) Write(w http.ResponseWriter) error

Write writes the response to the writer

type Route

type Route interface {
	Name() string
	Methods() []string
	Path() string
}

Route is the common route interface that should be implemented by handler functions

type RouteHook

type RouteHook func(r *http.Request, rt Route) error

RouteHook methods are called before the handler to allow for added context

type Router

type Router struct {
	*Server
	Mux *mux.Router
	// contains filtered or unexported fields
}

Router is an api Router

func (*Router) AddRoutes

func (r *Router) AddRoutes(routes ...Route) *Router

AddRoutes adds a routes to the router

func (Router) Name

func (r Router) Name() string

Name implements the Versioner interface

func (Router) RequireVersion

func (r Router) RequireVersion() bool

RequireVersion implements the Versioner interface

func (*Router) ServeHTTP

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

ServeHTTP implements the http.Handler interface

func (Router) Version

func (r Router) Version() string

Version implements the Versioner interface

func (*Router) WithName

func (r *Router) WithName(name string) RouterOption

WithName enables versioning that will enforce a versioned path

type RouterOption

type RouterOption func(r *Router)

RouterOption are router options

func WithAuthorizers

func WithAuthorizers(auth ...Authorizer) RouterOption

WithAuthorizers sets the authorizers for the router

func WithContext

func WithContext(ctx func(context.Context) interface{}) RouterOption

WithContext adds context to the router

func WithHooks

func WithHooks(hooks ...RouteHook) RouterOption

WithHooks sets the hooks for the router

func WithSessionManager

func WithSessionManager(store *session.Manager) RouterOption

WithSessionManager adds the session store to the router

func WithVersioning

func WithVersioning(version ...string) RouterOption

WithVersioning enables versioning that will enforce a versioned path

type Server

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

Server is an http server that provides basic REST funtionality

func NewServer

func NewServer(opts ...Option) *Server

NewServer creates a new server object

func (*Server) Log

func (s *Server) Log() log.Interface

Log returns the server log

func (*Server) LogMiddleware

func (s *Server) LogMiddleware() func(http.Handler) http.Handler

LogMiddleware is simple logging middleware handler

func (*Server) Name

func (s *Server) Name() string

Name implements the Versioner interface

func (*Server) RequireVersion

func (s *Server) RequireVersion() bool

RequireVersion implements the Versioner interface

func (*Server) Router

func (s *Server) Router(basePath string, opts ...RouterOption) *Router

Router returns an api router at the specified base path

func (*Server) Serve

func (s *Server) Serve() error

Serve starts the http server

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements the http.Handler interface

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown shuts down the http server with the context

func (*Server) Version

func (s *Server) Version() string

Version implements the Versioner interface

func (*Server) WriteError

func (s *Server) WriteError(w http.ResponseWriter, status int, err error)

WriteError writes an error object

func (*Server) WriteJSON

func (s *Server) WriteJSON(w http.ResponseWriter, status int, v interface{}, pretty ...bool)

WriteJSON writes out json

type StatusError

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

StatusError is a basic status error others can sub

func (StatusError) Code added in v0.1.2

func (e StatusError) Code() string

Code returns the error code

func (StatusError) Detail

func (e StatusError) Detail() []string

Detail returns the error detail

func (StatusError) Error

func (e StatusError) Error() string

func (*StatusError) Is

func (e *StatusError) Is(target error) bool

Is implements the errors.Is interface

func (StatusError) Payload

func (e StatusError) Payload() interface{}

Payload implements the api.Responder interface

func (StatusError) Status

func (e StatusError) Status() int

Status implements the api.Responder interface

func (StatusError) WithCode added in v0.1.2

func (e StatusError) WithCode(code string) ErrorResponse

WithCode sets the error code for the response, the default is the http status

func (StatusError) WithDetail

func (e StatusError) WithDetail(detail ...interface{}) ErrorResponse

WithDetail returns the error with detail

func (StatusError) WithError

func (e StatusError) WithError(err error) ErrorResponse

WithError returns the error with an underlying error

func (StatusError) WithMessage

func (e StatusError) WithMessage(format string, args ...interface{}) ErrorResponse

WithMessage returns the error with a message

func (StatusError) WithStatus

func (e StatusError) WithStatus(status int) ErrorResponse

WithStatus returns the error with status

func (StatusError) Write

func (e StatusError) Write(w http.ResponseWriter) error

Write implements the api.Responder interface

type Versioner

type Versioner interface {
	Name() string
	Version() string
	RequireVersion() bool
}

Versioner provides a version

type WriterFunc

type WriterFunc func(w http.ResponseWriter, status int, payload interface{}, headers ...http.Header) error

WriterFunc is a response writer

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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