gimlet: github.com/tychoish/gimlet Index | Files | Directories

package gimlet

import "github.com/tychoish/gimlet"

Package gimlet is a toolkit for building JSON/HTTP interfaces (e.g. REST).

Gimlet builds on standard library and common tools for building web applciations (e.g. Negroni and gorilla,) and is only concerned with JSON/HTTP interfaces, and omits support for aspects of HTTP applications outside of the scope of JSON APIs (e.g. templating, sessions.) Gimilet attempts to provide minimal convinences on top of great infrastucture so that your application can omit boilerplate and you don't have to build potentially redundant infrastructure.

Index

Package Files

app.go counter.go framework.go framework_pagination.go framework_response.go handling.go handling_binary.go handling_html.go handling_json.go handling_text.go handling_yaml.go methods.go middleware_grip.go parsing.go routing.go

func GetJSON Uses

func GetJSON(r io.ReadCloser, data interface{}) error

GetJSON parses JSON from a io.ReadCloser (e.g. http/*Request.Body or http/*Response.Body) into an object specified by the request. Used in handler functiosn to retreve and parse data submitted by the client.

func GetVars Uses

func GetVars(r *http.Request) map[string]string

GetVars is a helper method that processes an http.Request and returns a map of strings to decoded strings for all arguments passed to the method in the URL. Use this helper function when writing handler functions.

func GetYAML Uses

func GetYAML(r io.ReadCloser, data interface{}) error

GetYAML parses YAML from a io.ReadCloser (e.g. http/*Request.Body or http/*Response.Body) into an object specified by the request. Used in handler functiosn to retreve and parse data submitted by the client.u

func NewAppLogger Uses

func NewAppLogger() negroni.Handler

NewAppLogger creates an logging middlear instance suitable for use with Negroni. Sets the logging configuration to be the same as the default global grip logging object.

func WriteBinary Uses

func WriteBinary(w http.ResponseWriter, data interface{})

WriteBinary writes the data, converted to a byte slice as possible, to the response body, with a successful status code.

func WriteBinaryResponse Uses

func WriteBinaryResponse(w http.ResponseWriter, code int, data interface{})

func WriteErrorBinary Uses

func WriteErrorBinary(w http.ResponseWriter, data interface{})

WriteErrorBinary write the data, converted to a byte slice as possible, to the response body with a bad-request (e.g. 400) response code.

func WriteErrorHTML Uses

func WriteErrorHTML(w http.ResponseWriter, data interface{})

WriteErrorHTML write the data, converted to text as possible, to the response body as HTML with a bad-request (e.g. 400) response code.

func WriteErrorJSON Uses

func WriteErrorJSON(w http.ResponseWriter, data interface{})

WriteErrorJSON is a helper method to write JSON data to the body of an HTTP request and return 400 (user error.)

func WriteErrorText Uses

func WriteErrorText(w http.ResponseWriter, data interface{})

WriteErrorText write the data, converted to text as possible, to the response body with a bad-request (e.g. 400) response code.

func WriteErrorYAML Uses

func WriteErrorYAML(w http.ResponseWriter, data interface{})

WriteErrorYAML is a helper method to write YAML data to the body of an HTTP request and return 400 (user error.)

func WriteHTML Uses

func WriteHTML(w http.ResponseWriter, data interface{})

WriteHTML writes the data, converted to text as possible, to the response body as HTML with a successful status code.

func WriteHTMLResponse Uses

func WriteHTMLResponse(w http.ResponseWriter, code int, data interface{})

WriteHTMLResponse writes an HTML response with the specified error code.

func WriteInternalErrorBinary Uses

func WriteInternalErrorBinary(w http.ResponseWriter, data interface{})

WriteInternalErrorBinary write the data, converted to a byte slice as possible, to the response body with an internal server error (e.g. 500) response code.

func WriteInternalErrorHTML Uses

func WriteInternalErrorHTML(w http.ResponseWriter, data interface{})

WriteErrorHTML write the data, converted to text as possible, to the response body as HTML with an internal server error (e.g. 500) response code.

func WriteInternalErrorJSON Uses

func WriteInternalErrorJSON(w http.ResponseWriter, data interface{})

WriteInternalErrorJSON is a helper method to write JSON data to the body of an HTTP request and return 500 (internal error.)

func WriteInternalErrorText Uses

func WriteInternalErrorText(w http.ResponseWriter, data interface{})

WriteInternalErrorText write the data, converted to text as possible, to the response body with an internal server error (e.g. 500) response code.

func WriteInternalErrorYAML Uses

func WriteInternalErrorYAML(w http.ResponseWriter, data interface{})

WriteInternalErrorYAML is a helper method to write YAML data to the body of an HTTP request and return 500 (internal error.)

func WriteJSON Uses

func WriteJSON(w http.ResponseWriter, data interface{})

WriteJSON is a helper method to write JSON data to the body of an HTTP request and return 200 (successful.)

func WriteJSONResponse Uses

func WriteJSONResponse(w http.ResponseWriter, code int, data interface{})

WriteJSONResponse writes a JSON document to the body of an HTTP request, setting the return status of to 500 if the JSON seralization process encounters an error, otherwise return

func WriteText Uses

func WriteText(w http.ResponseWriter, data interface{})

WriteText writes the data, converted to text as possible, to the response body, with a successful status code.

func WriteTextResponse Uses

func WriteTextResponse(w http.ResponseWriter, code int, data interface{})

WriteTextResponse writes data to the response body with the given code as plain text after attempting to convert the data to a byte array.

func WriteYAML Uses

func WriteYAML(w http.ResponseWriter, data interface{})

WriteYAML is a helper method to write YAML data to the body of an HTTP request and return 200 (successful.)

func WriteYAMLResponse Uses

func WriteYAMLResponse(w http.ResponseWriter, code int, data interface{})

WriteYAMLResponse writes a YAML document to the body of an HTTP request, setting the return status of to 500 if the YAML seralization process encounters an error, otherwise return

type APIApp Uses

type APIApp struct {
    StrictSlash bool
    // contains filtered or unexported fields
}

APIApp is a structure representing a single API service.

func NewApp Uses

func NewApp() *APIApp

NewApp returns a pointer to an application instance. These instances have reasonable defaults and include middleware to: recover from panics in handlers, log information about the request, and gzip compress all data. Users must specify a default version for new methods.

func (*APIApp) AddApp Uses

func (a *APIApp) AddApp(app *APIApp) error

AddApp allows you to combine App instances, by taking one app and add its routes to the current app. Returns a non-nill error value if the current app is resolved. If the apps have different default versions set, the versions on the second app are explicitly set.

func (*APIApp) AddMiddleware Uses

func (a *APIApp) AddMiddleware(m negroni.Handler)

AddMiddleware adds a negroni handler as middleware to the end of the current list of middleware handlers.

func (*APIApp) AddRoute Uses

func (a *APIApp) AddRoute(r string) *APIRoute

AddRoute is the primary method for creating and registering a new route with an application. Use as the root of a method chain, passing this method the path of the route.

func (*APIApp) ResetMiddleware Uses

func (a *APIApp) ResetMiddleware()

ResetMiddleware removes *all* middleware handlers from the current application.

func (*APIApp) Resolve Uses

func (a *APIApp) Resolve() error

Resolve processes the data in an application instance, including all routes and creats a mux.Router object for the application instance.

func (*APIApp) Router Uses

func (a *APIApp) Router() (*mux.Router, error)

Router is the getter for an APIApp's router object. If thetr application isn't resolved, then the error return value is non-nil.

func (*APIApp) Run Uses

func (a *APIApp) Run() error

Run configured API service on the configured port. Before running the application, Run also resolves any sub-apps, and adds all routes.

func (*APIApp) SetDefaultVersion Uses

func (a *APIApp) SetDefaultVersion(version int)

SetDefaultVersion allows you to specify a default version for the application. Default versions must be 0 (no version,) or larger.

func (*APIApp) SetHost Uses

func (a *APIApp) SetHost(name string) error

SetHost sets the hostname or address for the application to listen on. Errors after resolving the application. You do not need to set this, and if unset the application will listen on the specified port on all interfaces.

func (*APIApp) SetPort Uses

func (a *APIApp) SetPort(port int) error

SetPort allows users to configure a default port for the API service. Defaults to 3000, and return errors will refuse to set the port to something unreasonable.

func (*APIApp) SetPrefix Uses

func (a *APIApp) SetPrefix(p string)

SetPrefix sets the route prefix, adding a leading slash, "/", if neccessary.

type APIRoute Uses

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

APIRoute is a object that represents each route in the application and includes the route and associate internal metadata for the route.

func (*APIRoute) Delete Uses

func (r *APIRoute) Delete() *APIRoute

Delete is a chainable method to add a handler for the DELETE method to the current route. Routes may specify multiple methods.

func (*APIRoute) Get Uses

func (r *APIRoute) Get() *APIRoute

Get is a chainable method to add a handler for the GET method to the current route. Routes may specify multiple methods.

func (*APIRoute) Handler Uses

func (r *APIRoute) Handler(h http.HandlerFunc) *APIRoute

Handler makes it possible to register an http.HandlerFunc with a route. Chainable. The common pattern for implementing these functions is to write functions and methods in your application that *return* handler fucntions, so you can pass application state or other data into to the handlers when the applications start, without relying on either global state *or* running into complex typing issues.

func (*APIRoute) IsValid Uses

func (r *APIRoute) IsValid() bool

IsValid checks if a route has is valid and populated.

func (*APIRoute) Patch Uses

func (r *APIRoute) Patch() *APIRoute

Patch is a chainable method to add a handler for the PATCH method to the current route. Routes may specify multiple methods.

func (*APIRoute) Post Uses

func (r *APIRoute) Post() *APIRoute

Post is a chainable method to add a handler for the POST method to the current route. Routes may specify multiple methods.

func (*APIRoute) Put Uses

func (r *APIRoute) Put() *APIRoute

Put is a chainable method to add a handler for the PUT method to the current route. Routes may specify multiple methods.

func (*APIRoute) RouteHandler Uses

func (r *APIRoute) RouteHandler(h RouteHandler) *APIRoute

RouteHandler defines a handler defined using the RouteHandler interface, which provides additional infrastructure for defining handlers, to separate input parsing, business logic, and response generation.

func (*APIRoute) Version Uses

func (r *APIRoute) Version(version int) *APIRoute

Version allows you to specify an integer for the version of this route. Version is chainable.

type OutputFormat Uses

type OutputFormat int
const (
    JSON OutputFormat = iota
    TEXT
    HTML
    YAML
    BINARY
)

func (OutputFormat) ContentType Uses

func (o OutputFormat) ContentType() string

func (OutputFormat) IsValid Uses

func (o OutputFormat) IsValid() bool

func (OutputFormat) String Uses

func (o OutputFormat) String() string

type Page Uses

type Page struct {
    BaseURL         string
    KeyQueryParam   string
    LimitQueryParam string

    Key      string
    Limit    int
    Relation string
    // contains filtered or unexported fields
}

Page represents the metadata required to build pagination links. To build the page, the route must have access to the full realized path, including any extra query parameters, to make it possible to build the metadata.

func (p *Page) GetLink(route string) string

GetLink returns the pagination metadata for this page. It is called by the GetLinks function. Your code need not use this call directly in most cases, except for testing.

func (*Page) Validate Uses

func (p *Page) Validate() error

Validate ensures that the page has populated all of the required data. Additionally Validate parses the BaseURL, and *must* be called before GetLink.

type Responder Uses

type Responder interface {
    // Validate returns an error if the page is not properly
    // constructed, although it is implementation specific, what
    // constitutes an invalid page.
    Validate() error

    // The data aspect of the interface holds the body of the
    // response. Implementations may handle multiple calls to
    // AddData differently, and provide different levels of
    // validation.
    Data() interface{}
    AddData(interface{}) error

    // Format represents the serialization format (and/or MIME
    // type) of the data payload on output. These options are
    // defined in gimlet, which supports JSON, YAML, Plain Text,
    // HTML, and Binary.
    Format() OutputFormat
    SetFormat(OutputFormat) error

    // Status returns the HTTP static code for this
    // responses. SetStatus implementations should not allow users
    // to set invalid statuses.
    Status() int
    SetStatus(int) error

    // The ResponsePage methods add and return the pagination
    // metdata for this route.
    //
    // Implementations should return nil pages to have an
    // unpaginated response.
    Pages() *ResponsePages
    SetPages(*ResponsePages) error
}

Responder is an interface for constructing a response from a route. Fundamentally Responders are data types, and provide setters and getters to store data that

In general, users will use one of gimlets response implementations, though clients may wish to build their own implementations to provide features not present in the existing

func NewBasicResponder Uses

func NewBasicResponder(s int, f OutputFormat, data interface{}) (Responder, error)

NewBasicResponder constructs a Responder from the arguments passed to the constructor, though interface remains mutable.

This implementation only allows a single data object, and AddData will overwrite existing data as set.

func NewResponseBuilder Uses

func NewResponseBuilder() Responder

NewResponseBuilder constructs a Responder implementation that can be used to incrementally build a with successive calls to AddData().

type ResponsePages Uses

type ResponsePages struct {
    Next *Page
    Prev *Page
}

ResponsePages holds pagination metadata for a route built with the Responder interface.

The pagination types and methods are

func (r *ResponsePages) GetLinks(route string) string

GetLinks returns the strings for use in the links header

func (*ResponsePages) Validate Uses

func (r *ResponsePages) Validate() error

Validate checks each page, if present, and ensures that the pagination metadata are consistent.

type RouteHandler Uses

type RouteHandler interface {
    // Factory produces, this makes it possible for you to store
    // request-scoped data in the implementation of the Handler
    // rather than attaching data to the context. The factory
    // allows gimlet to, internally, reconstruct a handler interface
    // for every request.
    //
    // Factory is always called at the beginning of the request.
    Factory() RouteHandler

    // Parse makes it possible to modify the request context and
    // populate the implementation of the RouteHandler. This also
    // allows you to isolate your interaction with the request
    // object.
    Parse(context.Context, *http.Request) (context.Context, error)

    // Runs the core buinsess logic for the route, returning a
    // Responder interface to provide structure around returning
    //
    // Run methods do not return an error. Implementors are
    // responsible for forming a response, even in error cases.
    Run(context.Context) Responder
}

RouteHandler provides an alternate method for defining routes with the goals of separating the core operations of handling a rest result.

Directories

PathSynopsis
buildscriptsThe current vendoring solution supports both new and old style vendoring, via a trick: We commit all vendored code to the "vendor" directory, and then, if we're on a version/deployment of go that doesn't support new style vendoring, we symlink to "build/vendor/src" and add "build/vendor" to the gopath, which the render-gopath program generates inside of the makefile.
buildscripts/vendoringPackage vendoring provides a several variables used in vendoring buildscripts and function that reports (without any external dependencies) if the current environment requires legacy-style vendoring, or if its safe to use new-style vendoring.

Package gimlet imports 20 packages (graph) and is imported by 4 packages. Updated 2017-11-22. Refresh now. Tools for package owners.