web

package
v1.6.2 Latest Latest
Warning

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

Go to latest
Published: Dec 5, 2023 License: Apache-2.0 Imports: 35 Imported by: 0

Documentation

Index

Constants

View Source
const (
	LOGGERKEY key
)

Context keys

Variables

View Source
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)
	ErrUnauthorized               = NewError("Unauthorized", 105, http.StatusUnauthorized)

	ErrInvalidRequestFormat = NewError("Invalid request format", 201, http.StatusBadRequest)
)
View Source
var Ping = http.HandlerFunc(ping)

Ping is the ping HandlerFunc

View Source
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 CorsHandler

func CorsHandler(allowedOrigins []string, allowedHeaders []string) *cors.Cors

func CreateSign

func CreateSign(key string, u *url.URL) string

CreateSign returns signature for given u

func Created

func Created(w http.ResponseWriter, _ *http.Request)

func DecodeJSON

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

func GetLogger

func GetLogger(r *http.Request) log.Interface

GetLogger retrieves logger from request context.

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 NewRouter

func NewRouter(routes Routes) *mux.Router

NewRouter returns a new router

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 SetLogger

func SetLogger(r *http.Request, l log.Interface) *http.Request

SetLogger sets logger to request context.

func SignURL

func SignURL(key string, u *url.URL)

SignURL adds signature to u using key

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 ValidSign

func ValidSign(key string, u *url.URL) bool

ValidSign validates signature of u using key

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

type Middleware func(next http.Handler) http.Handler

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 WithAddr

func WithAddr(addr string) Option

WithAddr sets the listening address of the server.

func WithCORS

func WithCORS(c *cors.Cors) Option

func WithDefaultHandler

func WithDefaultHandler(handler http.Handler) Option

WithDefaultHandler sets the default handler for the router.

func WithPing

func WithPing(ping bool) Option

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

func WithPingPath(path string) Option

WithPingPath sets the path of the ping endpoint. The ping endpoint defaults to "/api/v1/ping".

func WithPort

func WithPort(port int) Option

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

type RequestFunc func(opentracing.Span, *http.Request) (*http.Request, error)

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 Delete

func Delete(path string, handler http.Handler) Route

Delete returns a new route for this params for a DELETE request

func Get

func Get(path string, handler http.Handler) Route

Get returns a new route for this params for a GET request

func NewRoute

func NewRoute(method, path string, handler http.Handler, opts ...RouteOption) Route

NewRoute returns a new route for this params.

func Patch

func Patch(path string, handler http.Handler) Route

Patch returns a new route for this params for a PATCH request

func Post

func Post(path string, handler http.Handler) Route

Post returns a new route for this params for a POST request

func Put

func Put(path string, handler http.Handler) Route

Put returns a new route for this params for a PUT request

func (Route) String

func (r Route) String() 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 Routes

type Routes []Route

Routes keeps all routes.

type Server

type Server interface {
	Run() error
	Stop(ctx context.Context) error
}

func New

func New(routes Routes, opts ...Option) Server

New returns new web instance that handle the given routes. If no port is given through the options, the port defined in the environment variable WEB_PORT will be used. If WEB_PORT is not defined, the default 8888 port is used.

type Validatable

type Validatable interface {
	Validate() []ValidationError
}

type ValidationError

type ValidationError struct {
	Field   string `json:"field"`
	Message string `json:"message"`
}

func NewValidationError

func NewValidationError(field, message string) ValidationError

type Web

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

Web is a generic webserver.

func (*Web) Run

func (w *Web) Run() error

Run starts the http server. It returns the error returned by http.Server.ListenAndServe, except if that error is http.ErrServerClosed.

func (*Web) Stop

func (w *Web) Stop(ctx context.Context) error

Stop gracefully shutdowns the http server.

Jump to

Keyboard shortcuts

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