Documentation ¶
Index ¶
- Constants
- Variables
- func Error(logger *log.Logger, w http.ResponseWriter, code int, err error, show bool)
- func FileServer(router Router, path string, root http.FileSystem)
- func GetNextURL(r *http.Request) (next string)
- func JSON(w http.ResponseWriter, r *http.Request, v interface{})
- func RedirectToNextURL(w http.ResponseWriter, r *http.Request, statusCode int)
- func RedirectWithNextURL(w http.ResponseWriter, r *http.Request, target string, statusCode int)
- type Config
- type Loader
- type M
- type Router
Constants ¶
const JSONEscapeHTMLKey = "JSONEscapeHTML"
JSONEscapeHTMLKey is a context key which can be used with JSON() to set HTML escaping to true.
Variables ¶
var NextKey = "next"
NextKey is the query param name used when redirecting.
Functions ¶
func Error ¶
Error logs the given error, as well as optionally returns the error back to the connection.
func FileServer ¶
func FileServer(router Router, path string, root http.FileSystem)
FileServer conveniently sets up a http.FileServer handler to serve static files from a http.FileSystem. "router" matches any servemux style router which has a Get() method (e.g. go-chi/chi.Router).
For example, mixing go-chi/chi + go-ricebox:
FileServer(r, "/static", rice.MustFindBox("static").HTTPBox())
func GetNextURL ¶
GetNextURL obtains the target url from the intermediary URL, allowing you to pass in a URL parameter (e.g. ?next=/some/authed/page) which you can redirect to after doing some task (e.g. authenticating).
For example:
if isAuthed(r) { if next := pt.GetNextURL(r); next != "" { pt.RedirectToNextURL(w, r, http.StatusFound) return } http.Redirect(w, r, "/some/home/page", http.StatusFound) return }
func JSON ¶
func JSON(w http.ResponseWriter, r *http.Request, v interface{})
JSON marshals 'v' to JSON, and setting the Content-Type as application/json. Note that this does NOT auto-escape HTML. If you would like to escape HTML, set the JSONEscapeHTMLKey context value to true.
JSON also supports prettification when the origin request has "?pretty=true" or similar.
func RedirectToNextURL ¶
func RedirectToNextURL(w http.ResponseWriter, r *http.Request, statusCode int)
RedirectToNextURL redirects to the url specified within the "next" query parameter. Do this after the task (e.g. after authenticating).
Example:
if auth(user, passwd) { pt.RedirectToNextURL(w, r, http.StatusTemporaryRedirect) return }
func RedirectWithNextURL ¶
RedirectWithNextURL redirects to another page and passes the next url param, (e.g. a login page). target is the target redirect page, and statusCode is the http code used when redirecting.
Example:
if !auth(user, passwd) { pt.RedirectWithNextURL(w, r, r.URL.EscapedPath(), http.StatusTemporaryRedirect) return }
Types ¶
type Config ¶
type Config struct { // CacheParsed caches the parsed version of the template in memory, // which is useful for production when templates aren't being loaded // while the application is running (or when you are using ricebox or // similar.) CacheParsed bool // Loader is the template loader to use to load a template. This can // be some kind of filesystem loader, or a assetfs/memory-based loader // (re: go-ricebox). // // For example: // rice.MustFindBox("static").Bytes Loader func(path string) ([]byte, error) FS fs.FS // DefaultCtx is an optional function which you can supply, which is // called every time the Render() function is called, which allows you // to add additional context variables to the ctx map. Useful if you are // adding variables to multiple handlers frequently. DefaultCtx func(http.ResponseWriter, *http.Request) (ctx map[string]interface{}) // NotFoundHandler is an optional handler which you can define when the // template cannot be found based on what's returned from the Loader // method. If this is not defined, the Render() function will panic, as // this indicates the use of an undefined template. NotFoundHandler http.HandlerFunc // ErrorLogger is an optional io.Writer which errors are written to. Note // that these are request-specific errors (e.g. error while writing to the // client). Almost all template execution errors will cause a panic. ErrorLogger io.Writer }
Config is the configuration which should be passed to New().
type Loader ¶
type Loader struct {
// contains filtered or unexported fields
}
Loader is a template loader and executor. This should be created as a global variable to execution speed.
func (*Loader) Render ¶
func (ld *Loader) Render(w http.ResponseWriter, r *http.Request, path string, rctx map[string]interface{})
Render is used to render a specific template, where "path" is the path within the provided Config.Loader. "ctx" is the extra context which can be provided and loaded within your template, however it is not required. All ctx keys will be loaded at the base level (in the template, you can just use "{{ yourvar }}"). In addition to this, there are a few predefined ctx keys:
url -> request.URL cachets -> The timestamp of when the loader was defined. This is useful to append at the end of your css/js/etc as a way of allowing the browser to not use the same cache after the application has been recompiled/restarted.
ctx keys can be overridden. The priority is:
- Context defined via Render().
- Context defined via the default context function.
- Default defined context by the package, mentioned above.
type M ¶
type M map[string]interface{}
M is a convenience alias for quickly building a map structure that is going out to a responder. Just a short-hand.
type Router ¶
type Router interface {
Get(pattern string, h http.HandlerFunc)
}
Router is a general interface which many common http routers should fit. See FileServer() for details.