rest

package module
v0.0.9 Latest Latest
Warning

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

Go to latest
Published: Mar 16, 2022 License: MIT Imports: 15 Imported by: 2

README

rest

library to simplify api creation (truly opinated)

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrBadRequest          = errors.New("400")
	ErrUnauthorized        = errors.New("401")
	ErrNotFound            = errors.New("404")
	ErrConflict            = errors.New("409")
	ErrUnprocessableEntity = errors.New("422")
)

HTTP errors

Functions

func BadRequest

func BadRequest(w http.ResponseWriter, r *http.Request, reason string)

BadRequest is a generic 400 response

func BadRequestValidation

func BadRequestValidation(w http.ResponseWriter, r *http.Request, reason string, validationErrors map[string]string)

BadRequestValidation is a generic 400 response describing the validation errors if any

func ErrorResponse

func ErrorResponse(w http.ResponseWriter, status int, reason string) int

ErrorResponse returns a formatted error

func Forbidden

func Forbidden(w http.ResponseWriter, r *http.Request, reason string)

Forbidden is a generic 403 response

func GetFromBody

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

GetFromBody is a simple function to fill an object from the Request

func Location

func Location(parts ...string) string

Location returns a location joining strings

func NotAllowed

func NotAllowed(w http.ResponseWriter, r *http.Request)

NotAllowed is a generic 405 response that will be returned if the router can match the method

func NotFound

func NotFound(w http.ResponseWriter, r *http.Request)

NotFound is a generic 404 response that will be returned if the router cannot match a route

func Response

func Response(w http.ResponseWriter, response interface{}, err error, desiredStatus int, location string) int

Response is a default func to return data

func ResponseErr

func ResponseErr(w http.ResponseWriter, err error) int

ResponseErr is the Response where a straight error cannot be assigned. Simplified for if err != nil

func Unauthorized

func Unauthorized(w http.ResponseWriter, r *http.Request)

Unauthorized is a generic 401 response

func UnprocessableEntity added in v0.0.8

func UnprocessableEntity(w http.ResponseWriter, r *http.Request)

UnprocessableEntity is a generic 422 response

Types

type APIEndpoint

type APIEndpoint struct {
	Handler APIHandler
	Matcher APIMatcher
}

APIEndpoint is the struct that holds the Handler and Matchers (if any) to build the router

type APIHandler

type APIHandler func(w http.ResponseWriter, r *http.Request, ps httprouter.Params)

APIHandler defines the handler function that will be used for each API endpoint

type APIMatcher

type APIMatcher []string

APIMatcher is an array of rules that must be applied for each request to ensure

the required input is being passed to the API

type HTTPErrorStatus

type HTTPErrorStatus struct {
	Code             int               `json:"code"`
	Message          string            `json:"message"`
	Reason           string            `json:"reason,omitempty"`
	ValidationErrors map[string]string `json:"validation_errors,omitempty"`
}

HTTPErrorStatus is the struct that user will receive as body. It can contain a reason

if we are controlling what to explain about the error.

type LogResponseWriter

type LogResponseWriter struct {
	http.ResponseWriter
	// contains filtered or unexported fields
}

LogResponseWriter is a wrapper to get the information metrics of the

http.ResponseWriter

func NewLogResponseWriter

func NewLogResponseWriter(w http.ResponseWriter) *LogResponseWriter

NewLogResponseWriter returns the wrapped http.ResponseWriter

func (*LogResponseWriter) Size

func (w *LogResponseWriter) Size() int

Size returns the amount of data transferred in bytes

func (*LogResponseWriter) Status

func (w *LogResponseWriter) Status() int

Status returns the http error code for the response

func (*LogResponseWriter) Write

func (w *LogResponseWriter) Write(p []byte) (n int, err error)

Write wraps the http.ResponseWriter.Write method

func (*LogResponseWriter) WriteHeader

func (w *LogResponseWriter) WriteHeader(statusCode int)

WriteHeader wraps the http.ResponseWriter.WriteHeader method

type Logging

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

Logging abstracts all log facilities simplifying its usage other libraries that need to log something will use this to have just one way to do the things

func NewLogging

func NewLogging(outputPaths, errorOutputPaths []string, debug bool) (*Logging, error)

NewLogging returns a loggin instance, if no output paths passed it will default to stderr

func (*Logging) Debug

func (l *Logging) Debug(source, msg string, fields ...zap.Field)

Debug writes a debug trace

func (*Logging) Error

func (l *Logging) Error(source, msg string, fields ...zap.Field)

Error writes an error trace

func (*Logging) Info

func (l *Logging) Info(source, msg string, fields ...zap.Field)

Info writes an info trace

func (*Logging) Logger

func (l *Logging) Logger() *zap.Logger

Logger returns the raw logger

type REST

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

REST holds all logic for the API defined

func New

func New(ipPort string, tlsCertificate, tlsKey, tlsCACert []byte, requireClientCert bool, logger *Logging) (*REST, error)

New returns a pointer to a REST struct that holds the interactions for the API

func (*REST) SetCertificate added in v0.0.7

func (rr *REST) SetCertificate(cert, key []byte) (err error)

SetCertificate allows to set the certificates on the fly

func (*REST) SetupRouter

func (rr *REST) SetupRouter(routes map[string]map[string]APIEndpoint)

SetupRouter builds a router for the REST API endpoints

func (*REST) Shutdown

func (rr *REST) Shutdown() error

Shutdown tells the http server to stop gracefully

func (*REST) Start

func (rr *REST) Start() error

Start runs the REST API blocking execution

Jump to

Keyboard shortcuts

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