Documentation
¶
Index ¶
- Variables
- func LoadTemplates(globDir string, funcs template.FuncMap) map[string]*template.Template
- func LoadTemplatesWithLayout(globDir string, funcs template.FuncMap) map[string]*template.Template
- func NewServer(opt *ServerOptions) *http.Server
- func SimpleErrorHandler(c *Context, err error) error
- func SimpleNotFoundHandler(c *Context) error
- type Context
- func (c *Context) Bytes(status int, data []byte) error
- func (c *Context) DecodeJSON(data interface{}) error
- func (c *Context) Empty(status int) error
- func (c *Context) Error(status int, msg string) error
- func (c *Context) File(fs http.FileSystem, fp string) error
- func (c *Context) GetHeader(key string) string
- func (c *Context) GetParams(key string) string
- func (c *Context) HTML(status int, data string) error
- func (c *Context) JSON(status int, data interface{}) error
- func (c *Context) Log(msg string, args ...interface{})
- func (c *Context) NotFound() error
- func (c *Context) Redirect(status int, url string) error
- func (c *Context) Render(status int, tmpl string, data interface{}) error
- func (c *Context) SetHeader(key, value string)
- func (c *Context) Stream(status int, r io.Reader) error
- func (c *Context) String(status int, data string) error
- type Error
- type ErrorHandler
- type Handler
- type Middleware
- type Mux
- func (m *Mux) File(url, file string, mw ...Middleware)
- func (m *Mux) Register(method, url string, handler Handler, mw ...Middleware)
- func (m *Mux) RegisterPrefix(prefix string, mw ...Middleware) RegisterFunc
- func (m *Mux) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (m *Mux) Static(dir string, fs http.FileSystem, mw ...Middleware)
- type MuxOptions
- type RegisterFunc
- type ServerOptions
Constants ¶
This section is empty.
Variables ¶
var ErrInvalidTemplate = errors.New("invalid template")
ErrInvalidTemplate is returned when you try to render a template with an unknown name.
Functions ¶
func LoadTemplates ¶
LoadTemplates is a helper for quickly loading template files from a dir (using a filepath.Glob pattern) and an optional FuncMap. The returned map can be used straight away in the Options{} struct for the web handler. Templates are sorted (and parsed) by their file names.
NOTE: it will cause a panic on any errors (cuz I think it's bad enough, while trying to start up the web server).
TODO: rewrite this helper to use embed.FS instead, after go1.16 has landed in feb 2021
(see https://tip.golang.org/pkg/embed/)
func LoadTemplatesWithLayout ¶
LoadTemplatesWithLayout works basicly in the same way as LoadTemplates, except (!) the first template will be used as the base layout for the other templates.
NOTE: the layout template will be unavailable to render stand alone
func NewServer ¶
func NewServer(opt *ServerOptions) *http.Server
NewServer creates and sets up a new http.Server, using safe settings that should make it safer to expose to the internet. Settings are sourced from better informed security people and their published works :)
func SimpleErrorHandler ¶
SimpleErrorHandler is the default handler for handling handler errors (that sounded sick). It checks if an error is a Error and sends it's status code and msg as the http response. If it's not, it simply sends an "500 internal server error" for all other errors.
func SimpleNotFoundHandler ¶
SimpleNotFoundHandler is the default "404 not found" handler. It simply calls http.NotFound()
Types ¶
type Context ¶
type Context struct { M *Mux W http.ResponseWriter R *http.Request P httprouter.Params }
Context is a convenience struct for easing the handling of a http request.
func (*Context) Bytes ¶
Bytes is a quick helper to send a response, with the contents of []byte{} as body. You should set a Content-Type header yourself.
func (*Context) DecodeJSON ¶
DecodeJSON is a helper for JSON decoding a request body.
func (*Context) Error ¶
Error returns an *Error to the client, with http response "status" and "msg" body.
func (*Context) File ¶
func (c *Context) File(fs http.FileSystem, fp string) error
File attemps to send the contents of a file, located at `fp` and opened using `fs`. Default behaviour: * File path will be cleaned and resolved * Dotfiles will be ignored (or not, optionally) * Directory listnings will be ignored (or optionally serve an index file instead) * Any paths ignored will serve a `NotFound()` response instead * Content-Type will be autodetected (see `http.ServeContent` for more info and other extra handling)
Warning: if http.Server timeouts are set too short, this write might time out. TODO: replace http.FileSystem with io/fs.FS when go1.16 lands
func (*Context) GetParams ¶
GetParams is a shortcut to get URL params, first one given by key. See https://pkgo.dev/github.com/julienschmidt/httprouter#Param for more info. It's safe to call when *Context.P == nil
func (*Context) HTML ¶
HTML is a helper to send a simple HTML body, with a 'text/html' Content-Type header.
func (*Context) JSON ¶
JSON is a helper for JSON encoding the data and sending it with a response status.
func (*Context) NotFound ¶
NotFound returns the result from the '404 not found' handler set at setup.
func (*Context) Redirect ¶
Redirect sends a redirection response. It also makes sure the response code is within range.
func (*Context) Render ¶
Render tries to render a HTML template (using tmpl as key for the Options.Template map, from the handler). Optional data can be provided for the template.
type Error ¶
type Error struct {
// contains filtered or unexported fields
}
Error is a custom error which also contains a http status code. Whenever a Handler returns this error, the error message and status code will be sent back to the client unaltered.
type ErrorHandler ¶
ErrorHandler is a sort of a Handler, but it also takes an error.
type Handler ¶
Handler is a shorter convenience function signature for http handlers, instead of func(http.ResponseWriter, *http.Request). It also allows for easier error handling.
type Middleware ¶
Middleware is a function signature used when wrapping a Handler in one or many Handler middlewares.
type Mux ¶
type Mux struct {
// contains filtered or unexported fields
}
Mux implements the http.Handler interface and allows you to easily register handlers and middleware with sane defaults. It uses github.com/julienschmidt/httprouter, for quick and easy routing.
func NewMux ¶
func NewMux(opt *MuxOptions) *Mux
NewMux returns a new Mux that implements the http.Handler interface and can be run with http.ListenAndServe(":8000", handler). You can optionally proved an MuxOptions struct with custom settings. Any panics caused by a registered handler will be caught and optionaly logged.
func (*Mux) File ¶
func (m *Mux) File(url, file string, mw ...Middleware)
File is a helper to serve a simple http GET response for a single file. If the file "disappears" while the server is running, a 404 Not found will be returned. NOTE: if the file doesn't exist at start up, it will cause a panic instead. You can optionally use middlewares too, the same way as in Register().
func (*Mux) Register ¶
func (m *Mux) Register(method, url string, handler Handler, mw ...Middleware)
Register registers a new handler for a certain http method and URL. It will also handle any errors returned from the handler, by responding to the erroring request with http.Error(). You can optionally use one or more http.Handler middleware. First middleware in the list will be executed first, and then it loops forward through all middlewares and lasty executes the request handler last.
func (*Mux) RegisterPrefix ¶
func (m *Mux) RegisterPrefix(prefix string, mw ...Middleware) RegisterFunc
RegisterPrefix returns a RegisterFunc function that you can call multiple times to register multiple handlers under a common URL prefix. You can optionally use middlewares too, the same way as in Register().
func (*Mux) ServeHTTP ¶
func (m *Mux) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements the http.Handler interface.
func (*Mux) Static ¶
func (m *Mux) Static(dir string, fs http.FileSystem, mw ...Middleware)
Static is a helper to serve a whole directory with static files. You can optionally use middlewares too, the same way as in Register().
type MuxOptions ¶
type MuxOptions struct { // Simple logger Log *log.Logger // Templates that can be rendered using context.Render() Templates map[string]*template.Template // HandleNotFound is a Handler that will be called for '404 not found" errors. If not set it will default to // the SimpleNotFoundHandler() handler. HandleNotFound Handler // HandleError is a ErrorHandler that will be called for all errors returned from a Handler (except for // "404 not found"). It defaults to SimpleErrorHandler(). HandleError ErrorHandler // Middlewares is a list of middlewares that will be globaly added to all handlers Middlewares []Middleware }
MuxOptions contains all the optional settings for a Mux.
type RegisterFunc ¶
RegisterFunc is a function signature used when you want to register multiple handlers under a common URL path. First string is method, second string is the URL and last field is the Handler you want to register.