Documentation
¶
Index ¶
- Constants
- Variables
- type Binder
- type Context
- func (c *Context) JSON(status int, value interface{}) error
- func (c *Context) Param(key string) string
- func (c *Context) Query(key string) string
- func (c *Context) Render(status int, r Renderer) error
- func (c *Context) Request() *http.Request
- func (c *Context) Response() *Response
- func (c *Context) Stream(status int, contentType string, reader io.Reader) error
- func (c *Context) String(status int, value string) error
- func (c *Context) XML(status int, value interface{}) error
- type Error
- type FileHandlerOptions
- type Group
- func (g *Group) Add(method, path string, handler Handler, middleware ...Middleware) *Group
- func (g *Group) DELETE(path string, handler Handler, middleware ...Middleware) *Group
- func (g *Group) Files(path string, opts FileHandlerOptions) *Group
- func (g *Group) GET(path string, handler Handler, middleware ...Middleware) *Group
- func (g *Group) HEAD(path string, handler Handler, middleware ...Middleware) *Group
- func (g *Group) Mount(subgroups ...*Group) *Group
- func (g *Group) OPTIONS(path string, handler Handler, middleware ...Middleware) *Group
- func (g *Group) POST(path string, handler Handler, middleware ...Middleware) *Group
- func (g *Group) PUT(path string, handler Handler, middleware ...Middleware) *Group
- func (g *Group) Use(middleware ...Middleware) *Group
- func (g *Group) WithPrefix(prefix string) *Group
- type Handler
- type JSONRenderer
- type Middleware
- type Next
- type Renderer
- type Response
- type Router
- type StreamRenderer
- type StringRenderer
- type Validator
- type XMLRenderer
Constants ¶
const ( HeaderAcceptEncoding = "Accept-Encoding" HeaderContentEncoding = "Content-Encoding" HeaderContentType = "Content-Type" HeaderVary = "Vary" )
Some well-known http header keys.
const ( MIMEApplicationForm = "application/x-www-form-urlencoded" MIMEApplicationJSON = "application/json" MIMEApplicationJSONCharsetUTF8 = MIMEApplicationJSON + "; " + charsetUTF8 MIMEApplicationXML = "application/xml" MIMEApplicationXMLCharsetUTF8 = MIMEApplicationXML + "; " + charsetUTF8 MIMEMultipartForm = "multipart/form-data" MIMEOctetStream = "application/octet-stream" MIMETextPlain = "text/plain" MIMETextPlainCharsetUTF8 = MIMETextPlain + "; " + charsetUTF8 MIMETextXML = "text/xml" MIMETextXMLCharsetUTF8 = MIMETextXML + "; " + charsetUTF8 )
Some well-known content types.
See https://www.iana.org/assignments/media-types/media-types.xhtml.
Variables ¶
var ( // ErrInvalidContext indicates the use of a context that does not match the required type. ErrInvalidContext = errors.New("invalid context type") )
Functions ¶
This section is empty.
Types ¶
type Binder ¶
type Binder interface { // Bind unmarshalls an incoming request. The first argument is the raw *http.Request.The second argument is the // target struct. Bind(*http.Request, interface{}) error }
A Binder is used to unmarshal incoming requests.
var ( // DefaultBinder is the default Binder implementation. // It handels unmarshalling of JSON and XML encoded payloads depending on the Content-Type header of the request. // If the Content-Type is neither JSON nor XML ErrBindSupportedContentType is returned. DefaultBinder Binder = defaultBinder{} // ErrBindUnsupportedContentType indicates that a request could not be bound, because the Content-Type is not // supported by the Binder implementation. ErrBindUnsupportedContentType = errors.New("cannot bind content type") )
type Context ¶
type Context struct {
// contains filtered or unexported fields
}
Context is the base for custom contexts. It is a container for the raw http request and response and provides convenience methods to access request-data and to write responses.
func (*Context) Param ¶
Param returns the path parameter of the current matched route. If the parameter does not exist, an empty string is returned instead.
router.GET("/users/:name", func(ctx *Context) error { return ctx.String(http.StatusOK, ctx.Param("name")) })
func (*Context) Query ¶
Query returns the query value for a given key. If the key does not exist, an empty string is returned instead.
// curl "localhost:8080/search?input=Does router performance matter in Go?" router.GET("/search", func(ctx *Context) error { return ctx.String(http.StatusOK, ctx.Query("input")) })
func (*Context) Render ¶
Render writes a generic response using the provided Renderer after the status-code is set.
type Error ¶
type Error struct { Status int `json:"status"` Message string `json:"message"` Cause error `json:"-"` }
Error is a user displayable error that is returned during request handling.
func NewError ¶
NewError creates a new Error and sets the http status code, which will be set when not handeled manually.
func (*Error) Unwrap ¶
Unwrap returns the wrapped cause. This is useful to test for specific errors.
err := NewError(http.StatusInternalServerError).WithCause(io.EOF) errors.Is(err, io.EOF) // true
func (*Error) WithCause ¶
WithCause adds an actual error to the Error, which can later be unwrapped and tested for.
func (*Error) WithMessage ¶
WithMessage adds a custom message to the Error. By default http.StatusText is used to create a message.
type FileHandlerOptions ¶
type FileHandlerOptions struct { // Fs is used to resolve files. Fs http.FileSystem // NotFound is the filename to use, when no file exists. If empty 404 is returned. NotFound string }
FileHandlerOptions define how static files are handled.
type Group ¶
type Group struct {
// contains filtered or unexported fields
}
A Group is a collection of routes. A Group may have a prefix, that is shared across all routes.
func (*Group) Add ¶
func (g *Group) Add(method, path string, handler Handler, middleware ...Middleware) *Group
Add adds a Handler to the Group.
func (*Group) DELETE ¶
func (g *Group) DELETE(path string, handler Handler, middleware ...Middleware) *Group
DELETE adds a Handler to the Group with the "DELETE" http method.
func (*Group) Files ¶
func (g *Group) Files(path string, opts FileHandlerOptions) *Group
Files adds a Handler for static files using http.ServeContent.
func (*Group) GET ¶
func (g *Group) GET(path string, handler Handler, middleware ...Middleware) *Group
GET adds a Handler to the Group with the "GET" http method.
func (*Group) HEAD ¶
func (g *Group) HEAD(path string, handler Handler, middleware ...Middleware) *Group
HEAD adds a Handler to the Group with the "HEAD" http method.
func (*Group) OPTIONS ¶
func (g *Group) OPTIONS(path string, handler Handler, middleware ...Middleware) *Group
OPTIONS adds a Handler to the Group with the "OPTIONS" http method.
func (*Group) POST ¶
func (g *Group) POST(path string, handler Handler, middleware ...Middleware) *Group
POST adds a Handler to the Group with the "POST" http method.
func (*Group) PUT ¶
func (g *Group) PUT(path string, handler Handler, middleware ...Middleware) *Group
PUT adds a Handler to the Group with the "PUT" http method.
func (*Group) Use ¶
func (g *Group) Use(middleware ...Middleware) *Group
Use adds a list of Middleware to all routes of the Group. Middleware added with this method are only used for routes that are added afterwards.
func (*Group) WithPrefix ¶
WithPrefix prepends the prefix to all routes of the Group.
type Handler ¶
type Handler interface{}
A Handler must be a func with either 1 or 2 arguments and returning an error. The first must be either *bottleneck.Context or a pointer to a struct, that embeds bottleneck.Context. The second is optional and, if provided, must be a pointer to a struct, which is used to unmarshal and validate request payloads.
type LoginRequest struct { Username string `json:"username"` Password string `json:"password"` } type LoginResponse struct { Message string `json:"message"` } func login(ctx *bottleneck.Context, req *LoginRequest) error { if req.Username == "AzureDiamond" && req.Password == "hunter2" { return ctx.JSON(http.StatusOK, LoginResponse{ Message: "Welcome home, AzureDiamond!" }) } return ctx.JSON(http.StatusUnauthorized, LoginResponse{ Message: "Nice try!" }) }
type JSONRenderer ¶
type JSONRenderer struct {
Value interface{}
}
JSONRenderer implements the Renderer interface.
func (JSONRenderer) Header ¶
func (JSONRenderer) Header(h http.Header)
Header sets the Content-Type to "application/json; charset=UTF8".
type Middleware ¶
type Middleware interface{}
A Middleware must be a func with exactly two arguments. The first must be either *bottleneck.Context or a pointer to a struct, that embeds bottleneck.Context. The second must be a Next func, that has to be called to continue the route handling.
type SessionContext struct { bottleneck.Context Username string } func checkLogin(ctx *SessionContext, next bottleneck.Next) error { if ctx.Username != "AzureDiamond" { return ctx.String(http.StatusForbidden, "Wrong person.") } return next() }
type Next ¶
type Next func() error
Next is the second argument for Middleware. When called it will continue the route handling and return future errors.
type Renderer ¶
type Renderer interface { // Header is called before Render and is used to set http headers. // The standard implementations use this method to set the response Content-Type. Header(http.Header) // Render is called after Header and is used to write the raw http body. Render(io.Writer) error }
A Renderer is a container type that wraps an abstract http response.
type Response ¶
type Response struct { // Status is the http status code that is set during WriteHeader. Status int // Writer is the raw http.ResponseWriter. It can be set in a middleware to change the way data is written. Writer http.ResponseWriter }
Response wraps a raw http.ResponseWriter and stores additional information, which is not tracked by the standard library.
func (*Response) WriteHeader ¶
WriteHeader sends an HTTP response header with the provided status code.
type Router ¶
A Router is a multiplexer for http requests.
func NewRouter ¶
func NewRouter(contextValue interface{}) *Router
NewRouter creates a new Router for a custom context. The provided contextValue is an example instance of the context, which is used to get its type.
type CustomContext struct { bottleneck.Context } router := NewRouter(CustomContext{}) router.Listen(":8080")
type StreamRenderer ¶
StreamRenderer implements the Renderer interface.
func (StreamRenderer) Header ¶
func (r StreamRenderer) Header(h http.Header)
Header sets the Content-Type to the value of ContentType.
type StringRenderer ¶
type StringRenderer struct { // String is the exact value written in Render String string }
StringRenderer implements the Renderer interface.
func (StringRenderer) Header ¶
func (StringRenderer) Header(h http.Header)
Header sets the Content-Type to "text/plain; charset=UTF8".
type Validator ¶
type Validator interface { // Validate validates an incoming request. The first argument is the raw *http.Request. The second argument is the // unmarshalled payload. Validate(*http.Request, interface{}) error }
A Validator is used to validate incoming requests.
var DefaultValidator Validator = defaultValidator{validator.New()}
DefaultValidator is the default Validator implementation using https://github.com/go-playground/validator.
type XMLRenderer ¶
type XMLRenderer struct {
Value interface{}
}
XMLRenderer implements the Renderer interface.
func (XMLRenderer) Header ¶
func (XMLRenderer) Header(h http.Header)
Header sets the Content-Type to "text/xml; charset=UTF8".