buffalo: github.com/gobuffalo/buffalo Index | Files | Directories

package buffalo

import "github.com/gobuffalo/buffalo"

Index

Package Files

app.go binding.go context.go default_context.go errors.go flash.go handler.go logger.go method_override.go middleware.go not_found.go options.go request_logger.go resource.go response.go route.go router.go session.go wrappers.go

Variables

var RequestLogger = RequestLoggerFunc

RequestLogger can be be overridden to a user specified function that can be used to log the request.

func MethodOverride Uses

func MethodOverride(res http.ResponseWriter, req *http.Request)

MethodOverride is the default implementation for the Options#MethodOverride. By default it will look for a form value name `_method` and change the request method if that is present and the original request is of type "POST". This is added automatically when using `Automatic` Buffalo, unless an alternative is defined in the Options.

func NotFoundHandler Uses

func NotFoundHandler(status int, err error, c Context) error

NotFoundHandler is the default ErrorHandler for 404 responses. In development mode it attempts to return useful debugging information. In production it defaults to use the http.NotFound handler.

func RegisterBinder Uses

func RegisterBinder(contentType string, fn BinderFunc)

RegisterBinder maps a request Content-Type (application/json) to a BinderFunc.

type App Uses

type App struct {
    Options
    // Middleware returns the current MiddlewareStack for the App/Group.
    Middleware    *MiddlewareStack
    ErrorHandlers ErrorHandlers
    // contains filtered or unexported fields
}

App is where it all happens! It holds on to options, the underlying router, the middleware, and more. Without an App you can't do much!

func Automatic Uses

func Automatic(opts Options) *App

Automatic returns a new instance of App with sane defaults, some not so sane defaults, and a few bits and pieces to make your life that much easier. You'll want to use this almost all of the time to build your applications.

https://www.youtube.com/watch?v=BKbOplYmjZM

func New Uses

func New(opts Options) *App

New returns a new instance of App, without any frills or thrills. Most people will want to use Automatic which adds some sane, and useful, defaults.

func (*App) ANY Uses

func (a *App) ANY(p string, h Handler)

ANY accepts a request across any HTTP method for the specified path and routes it to the specified Handler.

func (*App) DELETE Uses

func (a *App) DELETE(p string, h Handler) RouteInfo

DELETE maps an HTTP "DELETE" request to the path and the specified handler.

func (*App) GET Uses

func (a *App) GET(p string, h Handler) RouteInfo

GET maps an HTTP "GET" request to the path and the specified handler.

func (*App) Group Uses

func (a *App) Group(groupPath string) *App

Group creates a new `*App` that inherits from it's parent `*App`. This is useful for creating groups of end-points that need to share common functionality, like middleware.

g := a.Group("/api/v1")
g.Use(AuthorizeAPIMiddleware)
g.GET("/users, APIUsersHandler)
g.GET("/users/:user_id, APIUserShowHandler)

func (*App) HEAD Uses

func (a *App) HEAD(p string, h Handler) RouteInfo

HEAD maps an HTTP "HEAD" request to the path and the specified handler.

func (*App) OPTIONS Uses

func (a *App) OPTIONS(p string, h Handler) RouteInfo

OPTIONS maps an HTTP "OPTIONS" request to the path and the specified handler.

func (*App) PATCH Uses

func (a *App) PATCH(p string, h Handler) RouteInfo

PATCH maps an HTTP "PATCH" request to the path and the specified handler.

func (*App) POST Uses

func (a *App) POST(p string, h Handler) RouteInfo

POST maps an HTTP "POST" request to the path and the specified handler.

func (*App) PUT Uses

func (a *App) PUT(p string, h Handler) RouteInfo

PUT maps an HTTP "PUT" request to the path and the specified handler.

func (*App) Redirect Uses

func (a *App) Redirect(status int, from, to string) RouteInfo

Redirect from one URL to another URL. Only works for "GET" requests.

func (*App) Resource Uses

func (a *App) Resource(p string, r Resource) *App

Resource maps an implementation of the Resource interface to the appropriate RESTful mappings. Resource returns the *App associated with this group of mappings so you can set middleware, etc... on that group, just as if you had used the a.Group functionality.

a.Resource("/users", &UsersResource{})

// Is equal to this:

ur := &UsersResource{}
g := a.Group("/users")
g.GET("/", ur.List) // GET /users => ur.List
g.GET("/new", ur.New) // GET /users/new => ur.New
g.GET("/{user_id}", ur.Show) // GET /users/{user_id} => ur.Show
g.GET("/{user_id}/edit", ur.Edit) // GET /users/{user_id}/edit => ur.Edit
g.POST("/", ur.Create) // POST /users => ur.Create
g.PUT("/{user_id}", ur.Update) PUT /users/{user_id} => ur.Update
g.DELETE("/{user_id}", ur.Destroy) DELETE /users/{user_id} => ur.Destroy

func (*App) Routes Uses

func (a *App) Routes() RouteList

Routes returns a list of all of the routes defined in this application.

func (*App) ServeFiles Uses

func (a *App) ServeFiles(p string, root http.FileSystem)

ServeFiles maps an path to a directory on disk to serve static files. Useful for JavaScript, images, CSS, etc...

a.ServeFiles("/assets", http.Dir("path/to/assets"))

func (*App) ServeHTTP Uses

func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*App) Use Uses

func (a *App) Use(mw ...MiddlewareFunc)

Use the specified Middleware for the App. When defined on an `*App` the specified middleware will be inherited by any `Group` calls that are made on that on the App.

type BaseResource Uses

type BaseResource struct{}

BaseResource fills in the gaps for any Resource interface functions you don't want/need to implement.

type UsersResource struct {
	Resource
}

func (ur *UsersResource) List(c Context) error {
	return c.Render(200, render.String("hello")
}

// This will fulfill the Resource interface, despite only having
// one of the functions defined.
&UsersResource{&BaseResource{})

func (*BaseResource) Create Uses

func (v *BaseResource) Create(c Context) error

Create default implementation. Returns a 404

func (*BaseResource) Destroy Uses

func (v *BaseResource) Destroy(c Context) error

Destroy default implementation. Returns a 404

func (*BaseResource) Edit Uses

func (v *BaseResource) Edit(c Context) error

Edit default implementation. Returns a 404

func (*BaseResource) List Uses

func (v *BaseResource) List(c Context) error

List default implementation. Returns a 404

func (*BaseResource) New Uses

func (v *BaseResource) New(c Context) error

New default implementation. Returns a 404

func (*BaseResource) Show Uses

func (v *BaseResource) Show(c Context) error

Show default implementation. Returns a 404

func (*BaseResource) Update Uses

func (v *BaseResource) Update(c Context) error

Update default implementation. Returns a 404

type BinderFunc Uses

type BinderFunc func(*http.Request, interface{}) error

BinderFunc takes a request and binds it to an interface. If there is a problem it should return an error.

type Context Uses

type Context interface {
    context.Context
    Response() http.ResponseWriter
    Request() *http.Request
    Session() *Session
    Params() ParamValues
    Param(string) string
    ParamInt(string) (int, error)
    Set(string, interface{})
    Get(string) interface{}
    LogField(string, interface{})
    LogFields(map[string]interface{})
    Logger() Logger
    Bind(interface{}) error
    Render(int, render.Renderer) error
    Error(int, error) error
    Websocket() (*websocket.Conn, error)
    Redirect(int, string, ...interface{}) error
    Data() map[string]interface{}
    Flash() *Flash
}

Context holds on to information as you pass it down through middleware, Handlers, templates, etc... It strives to make your life a happier one.

type DefaultContext Uses

type DefaultContext struct {
    context.Context
    // contains filtered or unexported fields
}

DefaultContext is, as its name implies, a default implementation of the Context interface.

func (*DefaultContext) Bind Uses

func (d *DefaultContext) Bind(value interface{}) error

Bind the interface to the request.Body. The type of binding is dependent on the "Content-Type" for the request. If the type is "application/json" it will use "json.NewDecoder". If the type is "application/xml" it will use "xml.NewDecoder". The default binder is "http://www.gorillatoolkit.org/pkg/schema".

func (*DefaultContext) Data Uses

func (d *DefaultContext) Data() map[string]interface{}

Data contains all the values set through Get/Set.

func (*DefaultContext) Error Uses

func (d *DefaultContext) Error(status int, err error) error

func (*DefaultContext) Flash Uses

func (d *DefaultContext) Flash() *Flash

Flash messages for the associated Request.

func (*DefaultContext) Get Uses

func (d *DefaultContext) Get(key string) interface{}

Get is deprecated. Please use Value instead.

func (*DefaultContext) LogField Uses

func (d *DefaultContext) LogField(key string, value interface{})

LogField adds the key/value pair onto the Logger to be printed out as part of the request logging. This allows you to easily add things like metrics (think DB times) to your request.

func (*DefaultContext) LogFields Uses

func (d *DefaultContext) LogFields(values map[string]interface{})

LogFields adds the key/value pairs onto the Logger to be printed out as part of the request logging. This allows you to easily add things like metrics (think DB times) to your request.

func (*DefaultContext) Logger Uses

func (d *DefaultContext) Logger() Logger

Logger returns the Logger for this context.

func (*DefaultContext) Param Uses

func (d *DefaultContext) Param(key string) string

Param returns a param, either named or query string, based on the key.

func (*DefaultContext) ParamInt Uses

func (d *DefaultContext) ParamInt(key string) (int, error)

ParamInt tries to convert the requested parameter to an int. It will return an error if there is a problem.

func (*DefaultContext) Params Uses

func (d *DefaultContext) Params() ParamValues

Params returns all of the parameters for the request, including both named params and query string parameters. These parameters are automatically available in templates as "{{.params}}".

func (*DefaultContext) Redirect Uses

func (d *DefaultContext) Redirect(status int, url string, args ...interface{}) error

Redirect a request with the given status to the given URL.

func (*DefaultContext) Render Uses

func (d *DefaultContext) Render(status int, rr render.Renderer) error

Render a status code and render.Renderer to the associated Response. The request parameters will be made available to the render.Renderer "{{.params}}". Any values set onto the Context will also automatically be made available to the render.Renderer. To render "no content" pass in a nil render.Renderer.

func (*DefaultContext) Request Uses

func (d *DefaultContext) Request() *http.Request

Request returns the original Request.

func (*DefaultContext) Response Uses

func (d *DefaultContext) Response() http.ResponseWriter

Response returns the original Response for the request.

func (*DefaultContext) Session Uses

func (d *DefaultContext) Session() *Session

Session for the associated Request.

func (*DefaultContext) Set Uses

func (d *DefaultContext) Set(key string, value interface{})

Set a value onto the Context. Any value set onto the Context will be automatically available in templates.

func (*DefaultContext) Value Uses

func (d *DefaultContext) Value(key interface{}) interface{}

Value that has previously stored on the context.

func (*DefaultContext) Websocket Uses

func (d *DefaultContext) Websocket() (*websocket.Conn, error)

Websocket returns an upgraded github.com/gorilla/websocket.Conn that can then be used to work with websockets easily.

type ErrorHandler Uses

type ErrorHandler func(int, error, Context) error

ErrorHandler interface for handling an error for a specific status code.

type ErrorHandlers Uses

type ErrorHandlers map[int]ErrorHandler

ErrorHandlers is used to hold a list of ErrorHandler types that can be used to handle specific status codes.

a.ErrorHandlers[500] = func(status int, err error, c buffalo.Context) error {
	res := c.Response()
	res.WriteHeader(status)
	res.Write([]byte(err.Error()))
	return nil
}

func (ErrorHandlers) Get Uses

func (e ErrorHandlers) Get(status int) ErrorHandler

Get a registered ErrorHandler for this status code. If no ErrorHandler has been registered, a default one will be returned.

type Flash Uses

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

Flash is a struct that helps with the operations over flash messages.

func (Flash) Add Uses

func (f Flash) Add(key, value string)

Add adds a flash value for a flash key, if the key already has values the list for that value grows.

func (*Flash) Clear Uses

func (f *Flash) Clear()

Clear removes all keys from the Flash.

func (Flash) Delete Uses

func (f Flash) Delete(key string)

Delete removes a particular key from the Flash.

func (Flash) Set Uses

func (f Flash) Set(key string, values []string)

Set allows to set a list of values into a particular key.

type HTTPError Uses

type HTTPError struct {
    Status int   `json:"status"`
    Cause  error `json:"error"`
}

HTTPError a typed error returned by http Handlers and used for choosing error handlers

func (HTTPError) Error Uses

func (h HTTPError) Error() string

type Handler Uses

type Handler func(Context) error

Handler is the basis for all of Buffalo. A Handler will be given a Context interface that represents the give request/response. It is the responsibility of the Handler to handle the request/response correctly. This could mean rendering a template, JSON, etc... or it could mean returning an error.

func (c Context) error {
	return c.Render(200, render.String("Hello World!"))
}

func (c Context) error {
	return c.Redirect(301, "http://github.com/gobuffalo/buffalo")
}

func (c Context) error {
	return c.Error(422, errors.New("oops!!"))
}

func RequestLoggerFunc Uses

func RequestLoggerFunc(h Handler) Handler

RequestLoggerFunc is the default implementation of the RequestLogger. By default it will log a uniq "request_id", the HTTP Method of the request, the path that was requested, the duration (time) it took to process the request, the size of the response (and the "human" size), and the status code of the response.

func WrapHandler Uses

func WrapHandler(h http.Handler) Handler

WrapHandler wraps a standard http.Handler and transforms it into a buffalo.Handler.

func WrapHandlerFunc Uses

func WrapHandlerFunc(h http.HandlerFunc) Handler

WrapHandlerFunc wraps a standard http.HandlerFunc and transforms it into a buffalo.Handler.

type Logger Uses

type Logger interface {
    WithField(string, interface{}) Logger
    WithFields(map[string]interface{}) Logger
    Debugf(string, ...interface{})
    Infof(string, ...interface{})
    Printf(string, ...interface{})
    Warnf(string, ...interface{})
    Errorf(string, ...interface{})
    Fatalf(string, ...interface{})
    Debug(...interface{})
    Info(...interface{})
    Warn(...interface{})
    Error(...interface{})
    Fatal(...interface{})
    Panic(...interface{})
}

Logger interface is used throughout Buffalo apps to log a whole manner of things.

func NewLogger Uses

func NewLogger(level string) Logger

NewLogger based on the specified log level. This logger will log to the STDOUT in a human readable, but parseable form.

Example: time="2016-12-01T21:02:07-05:00" level=info duration=225.283µs human_size="106 B" method=GET path="/" render=199.79µs request_id=2265736089 size=106 status=200

type MiddlewareFunc Uses

type MiddlewareFunc func(Handler) Handler

MiddlewareFunc defines the interface for a piece of Buffalo Middleware.

func DoSomething(next Handler) Handler {
	return func(c Context) error {
		// do something before calling the next handler
		err := next(c)
		// do something after call the handler
		return err
	}
}

type MiddlewareStack Uses

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

MiddlewareStack manages the middleware stack for an App/Group.

func (*MiddlewareStack) Clear Uses

func (ms *MiddlewareStack) Clear()

Clear wipes out the current middleware stack for the App/Group, any middleware previously defined will be removed leaving an empty middleware stack.

func (*MiddlewareStack) Replace Uses

func (ms *MiddlewareStack) Replace(mw1 MiddlewareFunc, mw2 MiddlewareFunc)

Replace a piece of middleware with another piece of middleware. Great for testing.

func (*MiddlewareStack) Skip Uses

func (ms *MiddlewareStack) Skip(mw MiddlewareFunc, handlers ...Handler)

Skip a specified piece of middleware the specified Handlers. This is useful for things like wrapping your application in an authorization middleare, but skipping it for things the home page, the login page, etc...

a.Middleware.Skip(Authorization, HomeHandler, LoginHandler, RegistrationHandler)

NOTE: When skipping Resource handlers, you need to first declare your resource handler as a type of buffalo.Resource for the Skip function to properly recognize and match it.

// Works:
var ur Resource
cr = &carsResource{&buffaloBaseResource{}}
g = a.Resource("/cars", cr)
g.Use(SomeMiddleware)
g.Middleware.Skip(SomeMiddleware, cr.Show)

// Doesn't Work:
cr := &carsResource{&buffaloBaseResource{}}
g = a.Resource("/cars", cr)
g.Use(SomeMiddleware)
g.Middleware.Skip(SomeMiddleware, cr.Show)

func (*MiddlewareStack) Use Uses

func (ms *MiddlewareStack) Use(mw ...MiddlewareFunc)

Use the specified Middleware for the App. When defined on an `*App` the specified middleware will be inherited by any `Group` calls that are made on that on the App.

type Options Uses

type Options struct {
    // Env is the "environment" in which the App is running. Default is "development".
    Env string
    // LogLevel defaults to "debug".
    LogLevel string
    // Logger to be used with the application. A default one is provided.
    Logger Logger
    // MethodOverride allows for changing of the request method type. See the default
    // implementation at buffalo.MethodOverride
    MethodOverride http.HandlerFunc
    // SessionStore is the `github.com/gorilla/sessions` store used to back
    // the session. It defaults to use a cookie store and the ENV variable
    // `SESSION_SECRET`.
    SessionStore sessions.Store
    // SessionName is the name of the session cookie that is set. This defaults
    // to "_buffalo_session".
    SessionName string
    // Host that this application will be available at. Default is "http://127.0.0.1:[$PORT|3000]".
    Host string
    // contains filtered or unexported fields
}

Options are used to configure and define how your application should run.

func NewOptions Uses

func NewOptions() Options

NewOptions returns a new Options instance with sensible defaults

type ParamValues Uses

type ParamValues interface {
    Get(string) string
}

ParamValues will most commonly be url.Values, but isn't it great that you set your own? :)

type Resource Uses

type Resource interface {
    List(Context) error
    Show(Context) error
    New(Context) error
    Create(Context) error
    Edit(Context) error
    Update(Context) error
    Destroy(Context) error
}

Resource interface allows for the easy mapping of common RESTful actions to a set of paths. See the a.Resource documentation for more details. NOTE: When skipping Resource handlers, you need to first declare your resource handler as a type of buffalo.Resource for the Skip function to properly recognize and match it.

// Works:
var cr Resource
cr = &carsResource{&buffaloBaseResource{}}
g = a.Resource("/cars", cr)
g.Use(SomeMiddleware)
g.Middleware.Skip(SomeMiddleware, cr.Show)

// Doesn't Work:
cr := &carsResource{&buffaloBaseResource{}}
g = a.Resource("/cars", cr)
g.Use(SomeMiddleware)
g.Middleware.Skip(SomeMiddleware, cr.Show)

type RouteInfo Uses

type RouteInfo struct {
    Method      string     `json:"method"`
    Path        string     `json:"path"`
    HandlerName string     `json:"handler"`
    MuxRoute    *mux.Route `json:"-"`
    Handler     Handler    `json:"-"`
}

RouteInfo provides information about the underlying route that was built.

type RouteList Uses

type RouteList []RouteInfo

RouteList contains a mapping of the routes defined in the application. This listing contains, Method, Path, and the name of the Handler defined to process that route.

func (RouteList) Len Uses

func (a RouteList) Len() int

func (RouteList) Less Uses

func (a RouteList) Less(i, j int) bool

func (RouteList) Swap Uses

func (a RouteList) Swap(i, j int)

type Session Uses

type Session struct {
    Session *sessions.Session
    // contains filtered or unexported fields
}

Session wraps the "github.com/gorilla/sessions" API in something a little cleaner and a bit more useable.

func (*Session) Clear Uses

func (s *Session) Clear()

Clear the current session

func (*Session) Delete Uses

func (s *Session) Delete(name interface{})

Delete a value from the current session.

func (*Session) Get Uses

func (s *Session) Get(name interface{}) interface{}

Get a value from the current session.

func (*Session) Save Uses

func (s *Session) Save() error

Save the current session.

func (*Session) Set Uses

func (s *Session) Set(name, value interface{})

Set a value onto the current session. If a value with that name already exists it will be overridden with the new value.

Directories

PathSynopsis
buffalo
buffalo/cmd
buffalo/cmd/generate
examples/hello-world
examples/hello-world/actions
examples/hello-world/grifts
examples/html-crud
examples/html-crud/actions
examples/html-crud/grifts
examples/html-crud/models
examples/html-resource
examples/html-resource/actions
examples/html-resource/grifts
examples/html-resource/models
examples/json-crud
examples/json-crud/actions
examples/json-crud/grifts
examples/json-crud/models
examples/json-resource
examples/json-resource/actions
examples/json-resource/grifts
examples/json-resource/models
examples/simple_hello
examples/websockets
examples/websockets/actions
examples/websockets/grifts
grifts
middleware
render
render/resolvers

Package buffalo imports 37 packages (graph) and is imported by 10 packages. Updated 2017-03-25. Refresh now. Tools for package owners.