plumbus

package module
v0.0.0-...-63f9ede Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2016 License: MIT Imports: 14 Imported by: 0

README

plumbus - Turn any function into a net/http handler

A Flexible ServeMux and HandlerFunc - Use any function as a handler, as long as you implement a few interfaces to define how that function's arguments, results, and errors are mapped to the http request and response.

Arguments

Arguments must implement plumbus.FromRequest, which looks like:

type FromRequest interface {
	FromRequest(*http.Request) error
}

However, if (at most) one parameter does not implement this interface, then that parameter will be decoded from the request body as json instead, by using the standard encoding/json package (supporting other types in the future is possible).

Return Values

Return values must implement plumbus.ToResponse, which looks like:

type ToResponse interface {
	ToResponse(http.ResponseWriter) error
}

However, if (at most) one return value does not implement this interface, then that return value will be encoded to the response body as json instead, by using the standard encoding/json package (supporting other types in the future is possible).

Errors

If a function returns an error (must be the last return value), then the result will be a 500 internal server error and no additional information about the error will be shown. However, if the error also implements the plumbus.HTTPError interface then the response code will be obtained by calling error.ResponseCode(), and the response body will be obtained from calling error.Error(). The same is true for errors returned by calls to FromRequest and ToRequest. The plumbus.HTTPError interface looks like:

type HTTPError interface {
	error
	ResponseCode() int
}

Isn't Reflection too slow?

Probabaly for some uses, however you can also run the plumbus command line tool via go generate to use code generation in place of reflection and eliminate all per-request reflection. (there will still be a small amount of reflection during setup).

Routing on Methods

To route by HTTP methods, just pass a value of type plumbus.ByMethod as your handler. This type maps from HTTP methods to (flexible) handler functions.

mux := plumbus.NewServeMux()
mux.Handle("/user", &plumbus.ByMethod{
  GET: getUser,
  POST: createUser,
  //other methods supported, but all are optional
})

##Path Parameters Path parameters are also supported. Example:

//handles cases such as /user/10/info
mux.Handle("/user/:userId/info", userInfo)

the path parameters will be translated into request parameters (available on req.URL.Query() before your handler is called)

##TODO

  • Add a tutorial
  • Add plumbus.Params type
  • Document the automatic documentation feature
  • Configurable Logging

Documentation

Overview

A Flexible ServeMux and HandlerFunc - Implement interfaces to determine how function arguments, results, and errors are mapped to the http request and response. Then write functions instead of http.Handlers or http.HandlerFunc's

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Error

func Error(code int, msg string) error

func Errorf

func Errorf(code int, msg string, args ...interface{}) error

func HandleResponseError

func HandleResponseError(res http.ResponseWriter, req *http.Request, err error)

func HandlerFunc

func HandlerFunc(handler interface{}) http.Handler

func RegisterAdaptor

func RegisterAdaptor(typ reflect.Type, adaptor adaptorFunc)

func WrapError

func WrapError(code int, err error) error

Types

type ByMethod

type ByMethod struct {
	GET, POST, PUT, PATCH, DELETE, OPTIONS interface{}
}

type Documentation

type Documentation struct {
	Endpoints    []*Endpoint      `json:"endpoints"`
	Types        map[string]*Type `json:"types,omitempty"`
	Introduction []string
}

type Endpoint

type Endpoint struct {
	Method       string               `json:"method,omitempty"`
	Path         string               `json:"path"`
	Description  string               `json:"description,omitempty"`
	RequestBody  string               `json:"requestBody,omitempty"`
	ResponseBody string               `json:"responseBody,omitempty"`
	Params       map[string]ParamInfo `json:"params,omitempty"`
	Notes        []string             `json:"notes,omitempty"`
}

type FromRequest

type FromRequest generate.FromRequest

type HTTPError

type HTTPError generate.HTTPError

type ParamInfo

type ParamInfo struct {
	Type        string `json:"type"`
	Required    bool   `json:"required"`
	Description string `json:"description,omitempty"`
}

type Paths

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

func (*Paths) Handle

func (p *Paths) Handle(path string, handler interface{}, documentation ...string)

func (*Paths) ServeHTTP

func (p *Paths) ServeHTTP(res http.ResponseWriter, req *http.Request)

type ServeMux

type ServeMux struct {
	*Paths
}

func NewServeMux

func NewServeMux() *ServeMux

func (*ServeMux) Documentation

func (sm *ServeMux) Documentation(introduction ...string) *Documentation

func (*ServeMux) DocumentationHTML

func (sm *ServeMux) DocumentationHTML(intro ...string) http.Handler

func (*ServeMux) Handle

func (sm *ServeMux) Handle(route string, fn interface{}, documentation ...string)

type ToResponse

type ToResponse generate.ToResponse

type Type

type Type struct {
	Description string      `json:"description,omitempty"`
	Example     interface{} `json:"example"`
}

Directories

Path Synopsis
cmd
plumbus command
tests

Jump to

Keyboard shortcuts

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