buffalo

package module
Version: v0.17.3 Latest Latest
Warning

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

Go to latest
Published: Sep 1, 2021 License: MIT Imports: 55 Imported by: 563

README

PkgGoDev Tests Status Go Report Card Open Source Helpers

Buffalo

A Go web development eco-system, designed to make your project easier.

Buffalo helps you to generate a web project that already has everything from front-end (JavaScript, SCSS, etc.) to the back-end (database, routing, etc.) already hooked up and ready to run. From there it provides easy APIs to build your web application quickly in Go.

Buffalo isn't just a framework; it's a holistic web development environment and project structure that lets developers get straight to the business of, well, building their business.

I ❤️ web dev in go again - Brian Ketelsen

⚠️ Important

Buffalo works only with Go modules. GOPATH mode is likely to break most of the functionality of the Buffalo eco-system. Please see this blog post for more information.

Also, the Buffalo team actively gives support to the last 2 versions of Go, which at the moment are:

  • 1.16.x
  • 1.17.x

While Buffalo may work on older versions, we encourage you to upgrade to latest 2 versions of Go for a better development experience.

Documentation

Please visit http://gobuffalo.io for the latest documentation, examples, and more.

Quick Start

Shoulders of Giants

Buffalo would not be possible if not for all of the great projects it depends on. Please see SHOULDERS.md to see a list of them.

Templating

github.com/gobuffalo/plush - This templating package was chosen over the standard Go html/template package for a variety of reasons. The biggest of which is that it is significantly more flexible and easy to work with.

Routing

github.com/gorilla/mux - This router was chosen because of its stability and flexibility. There might be faster routers out there, but this one is definitely the most powerful!

Task Runner (Optional)

github.com/markbates/grift - If you're familiar with Rake tasks from Ruby, you'll be right at home using Grift. This package was chosen to allow for the easy running of simple, and common, tasks that most web applications need. Think things like seeding a database or taking in a CSV file and generating database records. Buffalo ships with an example routes task that prints of the defined routes and the function that handles those requests.

Models/ORM (Optional)

github.com/gobuffalo/pop - Accessing databases is nothing new in web applications. Pop, and its command line tool, Soda, were chosen because they strike a nice balance between simplifying common tasks, being idiomatic, and giving you the flexibility you need to build your app. Pop and Soda share the same core philosophies as Buffalo, so they were a natural choice.

Sessions, Cookies, WebSockets, and more

github.com/gorilla - The Gorilla toolkit is a great set of packages designed to improve upon the standard library for a variety of web-related packages. With these high-quality packages Buffalo can keep its "core" code to a minimum and focus on its goal of gluing them all together to make your life better.

Benchmarks

Oh, yeah, everyone wants benchmarks! What would a web framework be without its benchmarks? Well, guess what? I'm not giving you any! That's right. This is Go! I assure you that it is plenty fast enough for you. If you want benchmarks you can either a) check out any benchmarks that the GIANTS Buffalo is built upon having published, or b) run your own. I have no interest in playing the benchmark game, and neither should you.

Contributing

First, thank you so much for wanting to contribute! It means so much that you care enough to want to contribute. We appreciate every PR from the smallest of typos to the be biggest of features.

Here are the core rules to respect:

  • If you have any question, please consider using the Slack channel (-#buffalo-, #buffalo_fr or #buffalo-dev for contribution related questions) or Stack Overflow. We use GitHub issues for bug reports and feature requests only.
  • All contributors of this project are working on their free time: be patient and kind. :-
  • Consider opening an issue BEFORE creating a Pull request (PR): you won't lose your -ime on fixing non-existing bugs, or fixing the wrong bug. Also we can help you to produce the best PR!
  • All PRs MUST be opened against the development branch. If you want to write an ho--fix, we'll first fix the development branch before moving the patch to master branch.

WE WILL CLOSE ANY ISSUE OR PR NOT FOLLOWING THESE CORE RULES.

For the full contribution guidelines, please read CONTRIBUTING.

Documentation

Overview

Package buffalo is a Go web development eco-system, designed to make your life easier.

Buffalo helps you to generate a web project that already has everything from front-end (JavaScript, SCSS, etc.) to back-end (database, routing, etc.) already hooked up and ready to run. From there it provides easy APIs to build your web application quickly in Go.

Buffalo **isn't just a framework**, it's a holistic web development environment and project structure that **lets developers get straight to the business** of, well, building their business.

Index

Constants

View Source
const (
	// EvtAppStart is emitted when buffalo.App#Serve is called
	EvtAppStart = "buffalo:app:start"
	// EvtAppStartErr is emitted when an error occurs calling buffalo.App#Serve
	EvtAppStartErr = "buffalo:app:start:err"

	// EvtAppStop is emitted when buffalo.App#Stop is called
	EvtAppStop = "buffalo:app:stop"
	// EvtAppStopErr is emitted when an error occurs calling buffalo.App#Stop
	EvtAppStopErr = "buffalo:app:stop:err"

	// EvtRouteStarted is emitted when a requested route is being processed
	EvtRouteStarted = "buffalo:route:started"
	// EvtRouteFinished is emitted when a requested route is completed
	EvtRouteFinished = "buffalo:route:finished"
	// EvtRouteErr is emitted when there is a problem handling processing a route
	EvtRouteErr = "buffalo:route:err"

	// EvtWorkerStart is emitted when buffalo.App#Serve is called and workers are started
	EvtWorkerStart = "buffalo:worker:start"
	// EvtWorkerStartErr is emitted when an error occurs when starting workers
	EvtWorkerStartErr = "buffalo:worker:start:err"

	// EvtWorkerStop is emitted when buffalo.App#Stop is called and workers are stopped
	EvtWorkerStop = "buffalo:worker:stop"
	// EvtWorkerStopErr is emitted when an error occurs when stopping workers
	EvtWorkerStopErr = "buffalo:worker:stop:err"

	// EvtFailureErr is emitted when something can't be processed at all. it is a bad thing
	EvtFailureErr = "buffalo:failure:err"
)
View Source
const (
	// AssetsAgeVarName is the ENV variable used to specify max age when ServeFiles is used.
	AssetsAgeVarName = "ASSETS_MAX_AGE"
)

Variables

View Source
var RequestLogger = RequestLoggerFunc

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

Functions

func Grifts added in v0.9.1

func Grifts(app *App)

Grifts decorates the app with tasks

func LoadPlugins added in v0.13.14

func LoadPlugins() error

LoadPlugins will add listeners for any plugins that support "events"

func MethodOverride

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 `New` Buffalo, unless an alternative is defined in the Options.

func WrapBuffaloHandler added in v0.13.0

func WrapBuffaloHandler(h Handler) http.Handler

WrapBuffaloHandler wraps a buffalo.Handler to standard http.Handler

func WrapBuffaloHandlerFunc added in v0.13.0

func WrapBuffaloHandlerFunc(h Handler) http.HandlerFunc

WrapBuffaloHandlerFunc wraps a buffalo.Handler to standard http.HandlerFunc

Types

type App

type App struct {
	Options
	// Middleware returns the current MiddlewareStack for the App/Group.
	Middleware    *MiddlewareStack `json:"-"`
	ErrorHandlers ErrorHandlers    `json:"-"`

	// Routenamer for the app. This field provides the ability to override the
	// base route namer for something more specific to the app.
	RouteNamer RouteNamer
	// 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 New

func New(opts Options) *App

New returns a new instance of App and adds some sane, and useful, defaults.

func (*App) ANY

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

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

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

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

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

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

func (*App) Mount added in v0.9.4

func (a *App) Mount(p string, h http.Handler)

Mount mounts a http.Handler (or Buffalo app) and passes through all requests to it.

func muxer() http.Handler {
	f := func(res http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(res, "%s - %s", req.Method, req.URL.String())
	}
	mux := mux.NewRouter()
	mux.HandleFunc("/foo", f).Methods("GET")
	mux.HandleFunc("/bar", f).Methods("POST")
	mux.HandleFunc("/baz/baz", f).Methods("DELETE")
	return mux
}

a.Mount("/admin", muxer())

$ curl -X DELETE http://localhost:3000/admin/baz/baz

func (*App) Muxer added in v0.13.0

func (a *App) Muxer() *mux.Router

Muxer returns the underlying mux router to allow for advance configurations

func (*App) OPTIONS

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

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

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

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

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

func (*App) PanicHandler added in v0.8.2

func (a *App) PanicHandler(next Handler) Handler

PanicHandler recovers from panics gracefully and calls the error handling code for a 500 error.

func (*App) Redirect added in v0.7.3

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 added in v0.4.3

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) RouteHelpers added in v0.13.0

func (a *App) RouteHelpers() map[string]RouteHelperFunc

RouteHelpers returns a map of BuildPathHelper() for each route available in the app.

func (*App) Routes

func (a *App) Routes() RouteList

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

func (*App) Serve added in v0.10.1

func (a *App) Serve(srvs ...servers.Server) error

Serve the application at the specified address/port and listen for OS interrupt and kill signals and will attempt to stop the application gracefully. This will also start the Worker process, unless WorkerOff is enabled.

func (*App) ServeFiles

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

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

func (*App) Stop added in v0.9.0

func (a *App) Stop(err error) error

Stop the application and attempt to gracefully shutdown

func (*App) Use

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 added in v0.4.3

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(http.StatusOK, render.String("hello")
}

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

func (BaseResource) Create added in v0.4.3

func (v BaseResource) Create(c Context) error

Create default implementation. Returns a 404

func (BaseResource) Destroy added in v0.4.3

func (v BaseResource) Destroy(c Context) error

Destroy default implementation. Returns a 404

func (BaseResource) List added in v0.4.3

func (v BaseResource) List(c Context) error

List default implementation. Returns a 404

func (BaseResource) Show added in v0.4.3

func (v BaseResource) Show(c Context) error

Show default implementation. Returns a 404

func (BaseResource) Update added in v0.4.3

func (v BaseResource) Update(c Context) error

Update default implementation. Returns a 404

type Context

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

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 Cookies added in v0.9.3

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

Cookies allows you to easily get cookies from the request, and set cookies on the response.

func (*Cookies) Delete added in v0.9.3

func (c *Cookies) Delete(name string)

Delete sets a header that tells the browser to remove the cookie with the given name.

func (*Cookies) Get added in v0.9.3

func (c *Cookies) Get(name string) (string, error)

Get returns the value of the cookie with the given name. Returns http.ErrNoCookie if there's no cookie with that name in the request.

func (*Cookies) Set added in v0.9.3

func (c *Cookies) Set(name, value string, maxAge time.Duration)

Set a cookie on the response, which will expire after the given duration.

func (*Cookies) SetWithExpirationTime added in v0.9.3

func (c *Cookies) SetWithExpirationTime(name, value string, expires time.Time)

SetWithExpirationTime sets a cookie that will expire at a specific time. Note that the time is determined by the client's browser, so it might not expire at the expected time, for example if the client has changed the time on their computer.

func (*Cookies) SetWithPath added in v0.13.0

func (c *Cookies) SetWithPath(name, value, path string)

SetWithPath sets a cookie path on the server in which the cookie will be available on. If set to '/', the cookie will be available within the entire domain. If set to '/foo/', the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of domain.

type DefaultContext

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

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". See the github.com/gobuffalo/buffalo/binding package for more details.

func (*DefaultContext) Cookies added in v0.9.3

func (d *DefaultContext) Cookies() *Cookies

Cookies for the associated request and response.

func (*DefaultContext) Data

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

Data contains all the values set through Get/Set.

func (*DefaultContext) Error

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

func (*DefaultContext) File added in v0.10.3

func (d *DefaultContext) File(name string) (binding.File, error)

File returns an uploaded file by name, or an error

func (*DefaultContext) Flash added in v0.7.2

func (d *DefaultContext) Flash() *Flash

Flash messages for the associated Request.

func (*DefaultContext) LogField

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

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

func (d *DefaultContext) Logger() Logger

Logger returns the Logger for this context.

func (*DefaultContext) MarshalJSON added in v0.13.0

func (d *DefaultContext) MarshalJSON() ([]byte, error)

MarshalJSON implements json marshaling for the context

func (*DefaultContext) Param

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

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

func (*DefaultContext) Params

func (d *DefaultContext) Params() ParamValues

Params returns all of the parameters for the request, including both named params and query string parameters.

func (*DefaultContext) Redirect

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

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

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

Request returns the original Request.

func (*DefaultContext) Response

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

Response returns the original Response for the request.

func (*DefaultContext) Session

func (d *DefaultContext) Session() *Session

Session for the associated Request.

func (*DefaultContext) Set

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) String added in v0.9.0

func (d *DefaultContext) String() string

func (*DefaultContext) Value added in v0.7.2

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

Value that has previously stored on the context.

type ErrorHandler added in v0.7.1

type ErrorHandler func(int, error, Context) error

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

type ErrorHandlers added in v0.7.1

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[http.StatusInternalServerError] = func(status int, err error, c buffalo.Context) error {
	res := c.Response()
	res.WriteHeader(status)
	res.Write([]byte(err.Error()))
	return nil
}

func (ErrorHandlers) Default added in v0.14.0

func (e ErrorHandlers) Default(eh ErrorHandler)

Default sets an error handler should a status code not already be mapped. This will replace the original default error handler. This is a *catch-all* handler.

func (ErrorHandlers) Get added in v0.7.1

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 ErrorResponse added in v0.13.0

type ErrorResponse struct {
	XMLName xml.Name `json:"-" xml:"response"`
	Error   string   `json:"error" xml:"error"`
	Trace   string   `json:"trace,omitempty" xml:"trace,omitempty"`
	Code    int      `json:"code" xml:"code,attr"`
}

ErrorResponse is a used to display errors as JSON or XML

type Flash added in v0.7.2

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

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

func (Flash) Add added in v0.7.2

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 added in v0.7.2

func (f *Flash) Clear()

Clear removes all keys from the Flash.

func (Flash) Delete added in v0.7.2

func (f Flash) Delete(key string)

Delete removes a particular key from the Flash.

func (Flash) Set added in v0.7.2

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

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

type HTTPError added in v0.7.2

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 added in v0.7.2

func (h HTTPError) Error() string

type Handler

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(http.StatusOK, render.String("Hello World!"))
}

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

func (c Context) error {
	return c.Error(http.StatusUnprocessableEntity, fmt.Errorf("oops!!"))
}

func RequestLoggerFunc

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

func WrapHandler(h http.Handler) Handler

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

func WrapHandlerFunc

func WrapHandlerFunc(h http.HandlerFunc) Handler

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

type Logger

type Logger = logger.FieldLogger

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

type Middler added in v0.14.7

type Middler interface {
	Use() []MiddlewareFunc
}

Middler can be implemented to specify additional middleware specific to the resource

type MiddlewareFunc

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

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

MiddlewareStack manages the middleware stack for an App/Group.

func (*MiddlewareStack) Clear

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) Remove added in v0.15.1

func (ms *MiddlewareStack) Remove(mws ...MiddlewareFunc)

Remove the specified Middleware(s) for the App/group. This is useful when the middleware will be skipped by the entire group.

a.Middleware.Remove(Authorization)

func (*MiddlewareStack) Replace added in v0.5.0

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

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

func (*MiddlewareStack) Skip

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 middleware, but skipping it for things the home page, the login page, etc...

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

func (MiddlewareStack) String added in v0.9.1

func (ms MiddlewareStack) String() string

func (*MiddlewareStack) Use

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

type Options struct {
	Name string `json:"name"`
	// Addr is the bind address provided to http.Server. Default is "127.0.0.1:3000"
	// Can be set using ENV vars "ADDR" and "PORT".
	Addr string `json:"addr"`
	// Host that this application will be available at. Default is "http://127.0.0.1:[$PORT|3000]".
	Host string `json:"host"`

	// Env is the "environment" in which the App is running. Default is "development".
	Env string `json:"env"`

	// LogLevel defaults to "debug". Deprecated use LogLvl instead
	LogLevel string `json:"log_level"`
	// LogLevl defaults to logger.DebugLvl.
	LogLvl logger.Level `json:"log_lvl"`
	// Logger to be used with the application. A default one is provided.
	Logger Logger `json:"-"`

	// MethodOverride allows for changing of the request method type. See the default
	// implementation at buffalo.MethodOverride
	MethodOverride http.HandlerFunc `json:"-"`

	// 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 `json:"-"`
	// SessionName is the name of the session cookie that is set. This defaults
	// to "_buffalo_session".
	SessionName string `json:"session_name"`

	// Worker implements the Worker interface and can process tasks in the background.
	// Default is "github.com/gobuffalo/worker.Simple.
	Worker worker.Worker `json:"-"`
	// WorkerOff tells App.Start() whether to start the Worker process or not. Default is "false".
	WorkerOff bool `json:"worker_off"`

	// PreHandlers are http.Handlers that are called between the http.Server
	// and the buffalo Application.
	PreHandlers []http.Handler `json:"-"`
	// PreWare takes an http.Handler and returns and http.Handler
	// and acts as a pseudo-middleware between the http.Server and
	// a Buffalo application.
	PreWares []PreWare `json:"-"`

	// CompressFiles enables gzip compression of static files served by ServeFiles using
	// gorilla's CompressHandler (https://godoc.org/github.com/gorilla/handlers#CompressHandler).
	// Default is "false".
	CompressFiles bool `json:"compress_files"`

	Prefix  string          `json:"prefix"`
	Context context.Context `json:"-"`
	// contains filtered or unexported fields
}

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

func NewOptions

func NewOptions() Options

NewOptions returns a new Options instance with sensible defaults

type ParamValues

type ParamValues interface {
	Get(string) string
}

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

type PreWare added in v0.9.4

type PreWare func(http.Handler) http.Handler

PreWare takes an http.Handler and returns and http.Handler and acts as a pseudo-middleware between the http.Server and a Buffalo application.

type Resource added in v0.4.3

type Resource interface {
	List(Context) error
	Show(Context) error
	Create(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 Response added in v0.9.0

type Response struct {
	Status int
	Size   int
	http.ResponseWriter
}

Response implements the http.ResponseWriter interface and allows for the capture of the response status and size to be used for things like logging requests.

func (*Response) CloseNotify added in v0.9.0

func (w *Response) CloseNotify() <-chan bool

CloseNotify implements the http.CloseNotifier interface

func (*Response) Flush added in v0.9.0

func (w *Response) Flush()

Flush the response

func (*Response) Hijack added in v0.9.0

func (w *Response) Hijack() (net.Conn, *bufio.ReadWriter, error)

Hijack implements the http.Hijacker interface to allow for things like websockets.

func (*Response) Write added in v0.9.0

func (w *Response) Write(b []byte) (int, error)

Write the body of the response

func (*Response) WriteHeader added in v0.9.0

func (w *Response) WriteHeader(code int)

WriteHeader sets the status code for a response

type RouteHelperFunc added in v0.8.2

type RouteHelperFunc func(opts map[string]interface{}) (template.HTML, error)

RouteHelperFunc represents the function that takes the route and the opts and build the path

type RouteInfo added in v0.7.1

type RouteInfo struct {
	Method       string     `json:"method"`
	Path         string     `json:"path"`
	HandlerName  string     `json:"handler"`
	ResourceName string     `json:"resourceName,omitempty"`
	PathName     string     `json:"pathName"`
	Aliases      []string   `json:"aliases"`
	MuxRoute     *mux.Route `json:"-"`
	Handler      Handler    `json:"-"`
	App          *App       `json:"-"`
}

RouteInfo provides information about the underlying route that was built.

func (*RouteInfo) Alias added in v0.9.3

func (ri *RouteInfo) Alias(aliases ...string) *RouteInfo

Alias path patterns to the this route. This is not the same as a redirect.

func (*RouteInfo) BuildPathHelper added in v0.8.2

func (ri *RouteInfo) BuildPathHelper() RouteHelperFunc

BuildPathHelper Builds a routeHelperfunc for a particular RouteInfo

func (*RouteInfo) Name added in v0.8.2

func (ri *RouteInfo) Name(name string) *RouteInfo

Name allows users to set custom names for the routes.

func (RouteInfo) ServeHTTP added in v0.9.0

func (ri RouteInfo) ServeHTTP(res http.ResponseWriter, req *http.Request)

func (RouteInfo) String added in v0.9.0

func (ri RouteInfo) String() string

String returns a JSON representation of the RouteInfo

type RouteList

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

func (a RouteList) Len() int

func (RouteList) Less

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

func (RouteList) Lookup added in v0.13.0

func (a RouteList) Lookup(name string) (*RouteInfo, error)

Lookup search a specific PathName in the RouteList and return the *RouteInfo

func (RouteList) Swap

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

type RouteNamer added in v0.16.19

type RouteNamer interface {
	// NameRoute receives the path and returns the name
	// for the route.
	NameRoute(string) string
}

RouteNamer is in charge of naming a route from the path assigned, this name typically will be used if no name is assined with .Name(...).

type Session

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 added in v0.7.3

func (s *Session) Clear()

Clear the current session

func (*Session) Delete

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

Delete a value from the current session.

func (*Session) Get

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

Get a value from the current session.

func (*Session) GetOnce added in v0.9.1

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

GetOnce gets a value from the current session and then deletes it.

func (*Session) Save

func (s *Session) Save() error

Save the current session.

func (*Session) Set

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

Path Synopsis
packrd
You can use the "packr2 clean" command to clean up this, and any other packr generated files.
You can use the "packr2 clean" command to clean up this, and any other packr generated files.
internal

Jump to

Keyboard shortcuts

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