api

package module
v0.0.0-...-ac512e1 Latest Latest
Warning

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

Go to latest
Published: Jul 20, 2016 License: MIT Imports: 16 Imported by: 0

README

api

Golang package to wrap web API endpoints

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func HandleError

func HandleError(req *Req, err error)

func Must

func Must(data []byte, err error) []byte

Because `panic`s are caught by martini's Recovery handler, it can be used to return server-side errors (500). Some helpful text message should probably be sent, although not the technical error (which is printed in the log).

func Send

func Send(ctx context.Context, req *Req, rm ResponseMarshaller) error

Types

type API

type API struct {
	Endpoints  []Endpoint
	Middleware MiddlewareStack

	Prefix string
	// contains filtered or unexported fields
}

Top-level API structure

func New

func New(prefix string) *API

func (*API) Activate

func (api *API) Activate(r interface{}) error

Activate() registers all endpoints in the api to the provided router

func (*API) Add

func (api *API) Add(e Endpoint)

Add() adds an endpoint to the API

func (*API) Use

func (api *API) Use(mw Middleware)

Append a middleware to the middleware stack.

type DataSource

type DataSource interface {
	// FindOne returns a model from a parsed query
	FindOne(context.Context) (context.Context, error)

	// FindAll returns all objects specified in query
	FindAll(context.Context) (context.Context, error)

	// Create a new object and return its ID
	Create(context.Context) (context.Context, error)

	// Update an object and return its ID
	Update(context.Context) (context.Context, error)

	// Delete an object
	Delete(context.Context) (context.Context, error)
}

DataSource provides methods needed for CRUD.

type Encoder

type Encoder interface {
	Encode(v ...interface{}) ([]byte, error)
}

An Encoder implements an encoding format of values to be sent as response to requests on the API endpoints.

type Endpoint

type Endpoint struct {
	Method string
	Path   string

	// The middlewares to execute on the request.
	Middleware MiddlewareStack

	// Called after middleware stack was executed on the request
	Implementation func(ctx context.Context, r *Req)
}

An Endpoint is the structure representing an API endpoint encapsulating information needed to dispatch a request and generate documentation.

func (Endpoint) Handle

Handle is a httprouter.Handle function

func (Endpoint) HandlerFunc

func (e Endpoint) HandlerFunc() http.HandlerFunc

HandlerFunc converts an Endpoint to a http.HandlerFunc

func (Endpoint) Serve

func (e Endpoint) Serve(ctx context.Context, req *Req)

Serve dispatches an api.Req

func (Endpoint) ServeHTTP

func (e Endpoint) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements the http.Handler interface

func (Endpoint) Use

func (e Endpoint) Use(mw Middleware)

Append a middleware to the middleware stack.

type Error

type Error struct {
	ID     string `json:"id,omitempty"`
	Href   string `json:"href,omitempty"`
	Status string `json:"status,omitempty,required"`
	Code   string `json:"code,omitempty"`
	Title  string `json:"title,omitempty,required"`
	Detail string `json:"detail,omitempty"`
	Path   string `json:"path,omitempty"`
}

Error implements the jsonapi.org spec for errors

func NewError

func NewError(status int, title string) *Error

func WrapErr

func WrapErr(err error, status int) *Error

WrapErr automatically wraps a standard error to an api.Error

func (*Error) Add

func (e *Error) Add(f *Error) Errors

Add returns a stack of errors

func (*Error) Error

func (e *Error) Error() string

Error returns a nice string representation of an Error

func (*Error) HTTPBody

func (e *Error) HTTPBody() string

HTTPBody returns the body of an http response for the error

func (*Error) HTTPStatus

func (e *Error) HTTPStatus() int

HTTPStatus returns the int value of the error status

type Errors

type Errors struct {
	Err []*Error `json:"errors"`
}

ErrorStack represents several errors

func (*Errors) Add

func (s *Errors) Add(e *Error)

Add adds an error to a stack of error

func (Errors) Error

func (e Errors) Error() string

Error returns a nice string representation of an Error

func (Errors) HTTPBody

func (e Errors) HTTPBody() string

HTTPBody returns the body of an http response for the error

func (Errors) HTTPStatus

func (e Errors) HTTPStatus() int

HTTPStatus returns the int value of the error status

type Getter

type Getter interface {
	Get(string) string
	GetAll(string) []string
}

Value getter

type GetterSetter

type GetterSetter interface {
	Getter
	Setter
}

type Handler

type Handler interface {
	Serve(ctx context.Context, req *Req)
}

Handler

type HandlerFunc

type HandlerFunc func(context.Context, *Req)

HandlerFunc

func (HandlerFunc) Serve

func (f HandlerFunc) Serve(ctx context.Context, req *Req)

type JsonEncoder

type JsonEncoder struct{}

func (JsonEncoder) Encode

func (_ JsonEncoder) Encode(v ...interface{}) ([]byte, error)

jsonEncoder is an Encoder that produces JSON-formatted responses.

type Middleware

type Middleware interface {

	// TODO: wrapping middleware (i.e. for logging)
	// HandlerFunc to process the incoming request and
	// returns a http error code and error message if needed.
	Run(ctx context.Context, r *Req) (context.Context, error)

	// Name of the middleware for debugging
	Name() string
}

type MiddlewareFunc

type MiddlewareFunc func(ctx context.Context, r *Req) (context.Context, error)

MiddlewareFunc transforms a function with the right signature into a Middleware

func (MiddlewareFunc) Name

func (m MiddlewareFunc) Name() string

func (MiddlewareFunc) Run

type MiddlewareStack

type MiddlewareStack []Middleware

type Params

type Params struct {
	Values // A unified view of all the individual param maps below.

	Query Values // Parameters from the query string, e.g. /index?limit=10
	Form  Values // Parameters from the request body.
	Path  Values // Parameters from the url path e.g. /users/:id

	Files map[string][]*multipart.FileHeader // Files uploaded in a multipart form

	RequiredParams []string // The required that have to be present for the params to be valid
	// contains filtered or unexported fields
}

Wrapper for the request params.

func (*Params) Append

func (p *Params) Append(s string, v ...string)

Append implements the GetterSetter interface

func (*Params) Get

func (p *Params) Get(s string) string

Get implements the GetterSetter interface

func (*Params) GetAll

func (p *Params) GetAll(s string) []string

GetAll implements the GetterSetter interface

func (*Params) Set

func (p *Params) Set(s string, v string)

Set implements the GetterSetter interface

type Req

type Req struct {
	ID          string // The request id
	Response    http.ResponseWriter
	Request     *http.Request
	Params      *Params // Parameters from URL and form (including multipart). Keep in ctx instead?
	ContentType string  // Content-Type of the request
	// contains filtered or unexported fields
}

Req is a HTTP request wrapper giving you easy access to the params content type, and much more.

func NewReq

func NewReq(w http.ResponseWriter, r *http.Request, p *Params) *Req

func WrapHttpRouterReq

func WrapHttpRouterReq(w http.ResponseWriter, r *http.Request, ps httprouter.Params) *Req

WrapReq wraps a request dispatched by httprouter.

func WrapReq

func WrapReq(w http.ResponseWriter, r *http.Request) *Req

WrapReq wraps a standard request.

func (*Req) Decode

func (r *Req) Decode(v interface{}) error

Decode decodes a request body into the value pointed to by v.

func (*Req) JsonBody

func (r *Req) JsonBody() ([]byte, error)

JsonBody() extracts the body from a request as a byte array so it cam be unmarshalled if desired.

func (*Req) JsonForm

func (r *Req) JsonForm() ([]byte, error)

func (*Req) NoContent

func (r *Req) NoContent(code int)

NoContent sends a response with no body and a status code.

func (*Req) ParseParams

func (r *Req) ParseParams() error

ParseParams from form, multipart, and query

func (*Req) Redirect

func (r *Req) Redirect(code int, url string)

Redirect redirects the request using http.Redirect with status code.

func (*Req) ResolveContentType

func (r *Req) ResolveContentType() string

ResolveContentType extracts content type from the request.

func (*Req) ResponseStatus

func (r *Req) ResponseStatus() int

ResponseStatus returns the response status code if available yet (0 otherwise).

type RequestParser

type RequestParser interface {
	ParseRequest(context.Context, *Req) (context.Context, error)
}

type Resource

type Resource struct {
	Req    *Req
	Source DataSource
}

func NewResource

func NewResource(req *Req, source DataSource) *Resource

func (*Resource) Create

func (r *Resource) Create(ctx context.Context) (context.Context, error)

func (*Resource) Delete

func (r *Resource) Delete(ctx context.Context) (context.Context, error)

func (*Resource) HandleCreate

func (r *Resource) HandleCreate(ctx context.Context, rp RequestParser) (context.Context, error)

func (*Resource) HandleDelete

func (r *Resource) HandleDelete(ctx context.Context, rp RequestParser) (context.Context, error)

func (*Resource) HandleError

func (r *Resource) HandleError(err error)

func (*Resource) HandleIndex

func (r *Resource) HandleIndex(ctx context.Context, rp RequestParser) (context.Context, error)

func (*Resource) HandleRead

func (r *Resource) HandleRead(ctx context.Context, rp RequestParser) (context.Context, error)

func (*Resource) HandleUpdate

func (r *Resource) HandleUpdate(ctx context.Context, rp RequestParser) (context.Context, error)

func (*Resource) Index

func (r *Resource) Index(ctx context.Context) (context.Context, error)

func (*Resource) Read

func (r *Resource) Read(ctx context.Context) (context.Context, error)

func (*Resource) Send

func (r *Resource) Send(ctx context.Context, rm ResponseMarshaller) error

func (*Resource) Update

func (r *Resource) Update(ctx context.Context) (context.Context, error)

type ResponseMarshaller

type ResponseMarshaller interface {
	Body(context.Context) interface{}
	Headers(context.Context) map[string]string
	Status(context.Context) int
}

type Router

type Router interface {
	Add(method, path string, handler Handler)
}

Router is an interface that helps activating an API to different types of router libraries (pat, httprouter, http, etc.)

func WrapRouter

func WrapRouter(v interface{}) (Router, error)

Wrap a router to be used with Activate i.e. api.Activate(WrapRouter(router))

type Setter

type Setter interface {
	Set(key string, value string)
	Append(key string, value ...string)
}

Value setter

type Values

type Values map[string][]string

Converts a map or url.Values into a rest.Getter interface

func (Values) Append

func (v Values) Append(key string, value ...string)

func (Values) Contains

func (v Values) Contains(key, sep string) bool

func (Values) Get

func (v Values) Get(key string) string

func (Values) GetAll

func (v Values) GetAll(key string) []string

func (Values) Set

func (v Values) Set(key string, value string)

Jump to

Keyboard shortcuts

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