Documentation
¶
Index ¶
- Constants
- Variables
- func BadRequest(w http.ResponseWriter, errCode int, field string, messages ...string)
- func CorsHandler(allowedOrigins []string, allowedHeaders []string) *cors.Cors
- func CreateSign(key string, u *url.URL) string
- func Created(w http.ResponseWriter, _ *http.Request)
- func DecodeJSON(r *http.Request, v interface{}) error
- func GetLogger(r *http.Request) log.Interface
- func HandleError(w http.ResponseWriter, req *http.Request, err error)
- func HandleErrorResponse(w http.ResponseWriter, req *http.Request, err *ErrorResponse)
- func NewRouter(routes Routes) *mux.Router
- func NewServerMetrics() *serverMetrics
- func NotFound(w http.ResponseWriter, errCode int, resources ...string)
- func PayloadTooLarge(w http.ResponseWriter, errCode int, field string, messages ...string)
- func PreconditionFailed(w http.ResponseWriter, errCode int, field string, messages ...string)
- func SetLogger(r *http.Request, l log.Interface) *http.Request
- func SignURL(key string, u *url.URL)
- func TracedTransport(tracer opentracing.Tracer, t http.RoundTripper, operationName string) http.RoundTripper
- func TracingMiddleware(tracer opentracing.Tracer, operationName string) func(http.Handler) http.Handler
- func UnsupportedMediaType(w http.ResponseWriter, errCode int, field string, messages ...string)
- func ValidSign(key string, u *url.URL) bool
- func WriteJSON(w http.ResponseWriter, code int, value interface{})
- type ContextKey
- type EmptyResponse
- type ErrorResponse
- func FetchIntVar(r *http.Request, name string) (int, *ErrorResponse)
- func FetchStringVar(r *http.Request, name string) (string, *ErrorResponse)
- func NewBadRequest(message string) *ErrorResponse
- func NewBadRequestNotFound(field, resource string) *ErrorResponse
- func NewConflict(message string) *ErrorResponse
- func NewError(message string, code, httpStatus int) *ErrorResponse
- func NewForbidden(message string) *ErrorResponse
- func NewInternalError(err error) *ErrorResponse
- func NewLoginRequired() *ErrorResponse
- func NewNotFound(message string) *ErrorResponse
- func NewServiceUnavailable() *ErrorResponse
- func NewValidationErrorsResponse(errs []ValidationError) *ErrorResponse
- func ParseErrorResponse(body []byte) (*ErrorResponse, error)
- func ReadJSON(r *http.Request, v Validatable) *ErrorResponse
- type Middleware
- type Option
- type RequestFunc
- type ResponseError
- type Route
- func Delete(path string, handler http.Handler) Route
- func Get(path string, handler http.Handler) Route
- func NewRoute(method, path string, handler http.Handler, opts ...RouteOption) Route
- func Patch(path string, handler http.Handler) Route
- func Post(path string, handler http.Handler) Route
- func Put(path string, handler http.Handler) Route
- type RouteOption
- type Routes
- type Server
- type Validatable
- type ValidationError
- type Web
Constants ¶
const (
LOGGERKEY key
)
Context keys
Variables ¶
var ( ErrMissingAuthorizationHeader = NewError("Missing authorization header", 101, http.StatusUnauthorized) ErrInvalidAuthorizationHeader = NewError("Invalid authorization header", 102, http.StatusUnauthorized) ErrInvalidAccessToken = NewError("Invalid access token", 103, http.StatusUnauthorized) ErrInvalidCredentials = NewError("Invalid credentials", 104, http.StatusUnauthorized) ErrInvalidRequestFormat = NewError("Invalid request format", 201, http.StatusBadRequest) )
var Ping = http.HandlerFunc(ping)
Ping is the ping HandlerFunc
var ( // SessionContextKey is the request context key where session is kept SessionContextKey = ContextKey("session") )
Functions ¶
func BadRequest ¶
func BadRequest(w http.ResponseWriter, errCode int, field string, messages ...string)
BadRequest writes to the ResponseWriter a bad request error.
func CreateSign ¶
CreateSign returns signature for given u
func DecodeJSON ¶
func HandleError ¶
func HandleError(w http.ResponseWriter, req *http.Request, err error)
HandleError logs the error then responds with generic 500 message
func HandleErrorResponse ¶
func HandleErrorResponse(w http.ResponseWriter, req *http.Request, err *ErrorResponse)
func NewServerMetrics ¶
func NewServerMetrics() *serverMetrics
func NotFound ¶
func NotFound(w http.ResponseWriter, errCode int, resources ...string)
NotFound writes to the ResponseWriter a not found error.
func PayloadTooLarge ¶ added in v1.5.8
func PayloadTooLarge(w http.ResponseWriter, errCode int, field string, messages ...string)
func PreconditionFailed ¶ added in v1.5.8
func PreconditionFailed(w http.ResponseWriter, errCode int, field string, messages ...string)
func TracedTransport ¶
func TracedTransport(tracer opentracing.Tracer, t http.RoundTripper, operationName string) http.RoundTripper
TracedTransport takes a http.RoundTripper and returns a transport wrapper that implements RoundTrip with added tracing.
func TracingMiddleware ¶
func TracingMiddleware(tracer opentracing.Tracer, operationName string) func(http.Handler) http.Handler
TracingMiddleware returns a middleware that adds tracing information to a request.
func UnsupportedMediaType ¶ added in v1.5.7
func UnsupportedMediaType(w http.ResponseWriter, errCode int, field string, messages ...string)
UnsupportedMediaType writes to the ResponseWriter an unsupported media type error.
func WriteJSON ¶
func WriteJSON(w http.ResponseWriter, code int, value interface{})
WriteJSON encodes given value to JSON and responds with <code>
Types ¶
type ContextKey ¶
type ContextKey string
ContextKey is a type alias for string to prevent key collisions across packages
type EmptyResponse ¶
type EmptyResponse struct{}
type ErrorResponse ¶
type ErrorResponse struct { Messages []string `json:"messages"` Code int `json:"code"` Errors map[string][]string `json:"errors"` HTTPStatus int `json:"-"` // contains filtered or unexported fields }
ErrorResponse defines the response structure for all 4xx and 5xx errors
func FetchIntVar ¶
func FetchIntVar(r *http.Request, name string) (int, *ErrorResponse)
func FetchStringVar ¶
func FetchStringVar(r *http.Request, name string) (string, *ErrorResponse)
func NewBadRequest ¶
func NewBadRequest(message string) *ErrorResponse
NewValidationError returns a new error response with 400 status code
func NewBadRequestNotFound ¶
func NewBadRequestNotFound(field, resource string) *ErrorResponse
func NewConflict ¶
func NewConflict(message string) *ErrorResponse
NewConflict returns a new error response with 409 status code
func NewError ¶
func NewError(message string, code, httpStatus int) *ErrorResponse
func NewForbidden ¶
func NewForbidden(message string) *ErrorResponse
NewForbidden returns a new error response with 403 status code
func NewInternalError ¶
func NewInternalError(err error) *ErrorResponse
func NewLoginRequired ¶
func NewLoginRequired() *ErrorResponse
func NewNotFound ¶
func NewNotFound(message string) *ErrorResponse
NewNotFound returns a new error response with 404 status code
func NewServiceUnavailable ¶
func NewServiceUnavailable() *ErrorResponse
func NewValidationErrorsResponse ¶
func NewValidationErrorsResponse(errs []ValidationError) *ErrorResponse
func ParseErrorResponse ¶
func ParseErrorResponse(body []byte) (*ErrorResponse, error)
func ReadJSON ¶
func ReadJSON(r *http.Request, v Validatable) *ErrorResponse
func (*ErrorResponse) InternalError ¶
func (e *ErrorResponse) InternalError() error
func (*ErrorResponse) IsInternalError ¶
func (e *ErrorResponse) IsInternalError() bool
func (*ErrorResponse) Write ¶
func (e *ErrorResponse) Write(w http.ResponseWriter)
type Middleware ¶
Middleware defines an HTTP middleware: a decorator that takes an HTTP handler and returns an HTTP handler.
func MiddlewareChain ¶
func MiddlewareChain(middlewares ...Middleware) Middleware
MiddlewareChain returns a middleware composed of sequentially applied middlewares. It is implemented as a recursive function, where the first middleware wraps the resulted chain of the following middlewares.
type Option ¶
type Option func(*serverOptions)
Option is used to specify functional options when creating a new web server.
func WithDefaultHandler ¶
WithDefaultHandler sets the default handler for the router.
func WithPing ¶
WithPing can be used to disable the ping route by giving WithPing(false) as option to New(). The ping endpoint defaults to "/api/v1/ping". If you want to specify a custom path use `WithPingPath`.
func WithPingPath ¶
WithPingPath sets the path of the ping endpoint. The ping endpoint defaults to "/api/v1/ping".
func WithPort ¶
WithPort overrides the default port used by New(). The default port is the port given in the WEB_PORT environment variable, or 8888 if the environment variable is not set.
func WithTracer ¶
func WithTracer(tracer opentracing.Tracer) Option
WithTracer sets the tracer when creating a web server. The tracer will be added to each route.
type RequestFunc ¶
RequestFunc defines a function that receives a span and inserts it into the request context.
func TraceableRequestFunc ¶
func TraceableRequestFunc(tracer opentracing.Tracer) RequestFunc
TraceableRequestFunc returns a RequestFunc.
type ResponseError ¶
type ResponseError interface { AddMessage(message string) ResponseError With(key string, values ...string) ResponseError Write(w http.ResponseWriter) }
ResponseError defines an interface for HTTP error handling, using the custom format:
{ "messages": ["a message", "another message"], "errors": { "thing 1": ["value 1", "value 2"], "thing 2": ["value 3"] } }
func Error ¶
func Error(statusCode, errCode int) ResponseError
Error creates a ResponseError that also writes the error code to the response writer.
type Route ¶
type Route struct { Method string Pattern string Handler http.Handler // contains filtered or unexported fields }
Route object
func NewRoute ¶
func NewRoute(method, path string, handler http.Handler, opts ...RouteOption) Route
NewRoute returns a new route for this params.
func (Route) String ¶
String returns the name of the root as a combination of the method and the route pattern. E.g.: "POST /api/v1/devices/{uuid}"
func (Route) WithMiddlewares ¶
func (r Route) WithMiddlewares(middlewares ...Middleware) Route
WithMiddlewares returns a route with its handler wrapped with the given middlewares.
type RouteOption ¶
type RouteOption func(*Route)
RouteOption is a functional option for creating routes.
func WithPrefix ¶
func WithPrefix() RouteOption
WithPrefix adds a matcher for the URL path prefix for a route. See http://www.gorillatoolkit.org/pkg/mux#Route.PathPrefix for more details.
type Validatable ¶
type Validatable interface {
Validate() []ValidationError
}
type ValidationError ¶
func NewValidationError ¶
func NewValidationError(field, message string) ValidationError