Documentation ¶
Overview ¶
Package api is the hiro api helper library
Index ¶
- Constants
- Variables
- func AuthPrincipal(ctx context.Context, target interface{}) bool
- func Context(ctx context.Context) interface{}
- func IsRequest(ctx context.Context) bool
- func Log(ctx context.Context) log.Interface
- func Request(ctx context.Context) (*http.Request, http.ResponseWriter)
- func RequestHost(ctx context.Context) string
- func RequestVersion(r *http.Request) string
- func RequirePrincipal(ctx context.Context, target interface{}, t ...PrincipalType)
- func SessionManager(ctx context.Context) *session.Manager
- func Unauthorized(r *http.Request) (interface{}, error)
- func Version(ctx context.Context) string
- func VersionMiddleware(v Versioner, header ...string) func(http.Handler) http.Handler
- func Write(w http.ResponseWriter, status int, payload interface{}, headers ...http.Header) error
- func WriteJSON(w http.ResponseWriter, status int, payload interface{}, headers ...http.Header) error
- func WriteXML(w http.ResponseWriter, status int, payload interface{}, headers ...http.Header) error
- type AuthorizedRoute
- type Authorizer
- type AuthorizerFunc
- type CachedRoute
- type Claims
- type CredentialType
- type Encoder
- type ErrorResponse
- type HandlerFunc
- type Option
- func WithAddr(addr string) Option
- func WithBasepath(base string) Option
- func WithCORS(origin ...string) Option
- func WithCache(ttl time.Duration) Option
- func WithListener(l net.Listener) Option
- func WithLog(l log.Interface) Option
- func WithRouter(router *mux.Router) Option
- func WithServerName(name string) Option
- func WithTracing(t bool) Option
- func WithVersion(v string) Option
- type Principal
- type PrincipalType
- type Redirector
- type Responder
- type Response
- type Route
- type RouteHook
- type Router
- type RouterOption
- type Server
- func (s *Server) Log() log.Interface
- func (s *Server) LogMiddleware() func(http.Handler) http.Handler
- func (s *Server) Name() string
- func (s *Server) RequireVersion() bool
- func (s *Server) Router(basePath string, opts ...RouterOption) *Router
- func (s *Server) Serve() error
- func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (s *Server) Shutdown(ctx context.Context) error
- func (s *Server) Version() string
- func (s *Server) WriteError(w http.ResponseWriter, status int, err error)
- func (s *Server) WriteJSON(w http.ResponseWriter, status int, v interface{}, pretty ...bool)
- type StatusError
- func (e StatusError) Code() string
- func (e StatusError) Detail() []string
- func (e StatusError) Error() string
- func (e *StatusError) Is(target error) bool
- func (e StatusError) Payload() interface{}
- func (e StatusError) Status() int
- func (e StatusError) WithCode(code string) ErrorResponse
- func (e StatusError) WithDetail(detail ...interface{}) ErrorResponse
- func (e StatusError) WithError(err error) ErrorResponse
- func (e StatusError) WithMessage(format string, args ...interface{}) ErrorResponse
- func (e StatusError) WithStatus(status int) ErrorResponse
- func (e StatusError) Write(w http.ResponseWriter) error
- type Versioner
- type WriterFunc
Constants ¶
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 ¶
var ( // ErrBadRequest should be returned for a bad request or invalid parameters ErrBadRequest = Errorf("bad request").WithStatus(http.StatusBadRequest) 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 ¶
AuthPrincipal the first auth principal that matches the target
func RequestHost ¶ added in v0.1.1
RequestHost returns the host from the current request
func RequestVersion ¶
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 ¶
SessionManager returns the session store from the context
func Unauthorized ¶
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 VersionMiddleware ¶
VersionMiddleware enforces versioning in the request path
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 ¶
AuthorizerFunc performs an authorization and returns a context or error on failure
type CachedRoute ¶
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 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 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 WithBasepath ¶
WithBasepath sets the router basepath for the api
func WithListener ¶
WithListener sets the net listener for the server
func WithServerName ¶
WithServerName specifies the server name
func WithVersion ¶
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 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
RedirectErrIf does a conditional redirect with the error
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) WithHeader ¶
WithHeader adds headers to the request
func (*Response) WithStatus ¶
WithStatus sets the status
func (*Response) WithWriter ¶
func (r *Response) WithWriter(w WriterFunc) *Response
WithWriter sets the writer
type Router ¶
Router is an api Router
func (Router) RequireVersion ¶
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) 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 (*Server) LogMiddleware ¶
LogMiddleware is simple logging middleware handler
func (*Server) RequireVersion ¶
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) ServeHTTP ¶
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements the http.Handler interface
func (*Server) WriteError ¶
func (s *Server) WriteError(w http.ResponseWriter, status int, err error)
WriteError writes an error object
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) 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 WriterFunc ¶
type WriterFunc func(w http.ResponseWriter, status int, payload interface{}, headers ...http.Header) error
WriterFunc is a response writer