Documentation ¶
Overview ¶
The resp package provides a high-level API for responding to HTTP requests with an easy way to configure the responses application-wide.
resp provides three main ways of responding to an HTTP request: - rendering HTML templates - rendering JSON data - redirecting
Index ¶
- Variables
- func NoopResponderOptFn(_ *Responder)
- func WithAuthTemplate(fp string) func(*Responder)
- func WithContactErrMsg(msg string) func(*Responder)
- func WithCtxKeys(keys ...ctx.CtxKeyable) func(*Responder)
- func WithLogger(log logger.Logger) func(*Responder)
- func WithParser(p template.Parser) func(*Responder)
- func WithRootUrl(u string) func(*Responder)
- func WithSessionKey(key ctx.CtxKeyable) func(*Responder)
- func WithUnauthTemplate(fp string) func(*Responder)
- func WithUserSessionKey(key ctx.CtxKeyable) func(*Responder)
- func WithVueTemplate(fp string) func(*Responder)
- type Fn
- func Authed() Fn
- func Code(c int) Fn
- func Data(d map[string]interface{}) Fn
- func Err(e error) Fn
- func Flash(flash session.Flash) Fn
- func GenericErr(e error) Fn
- func Param(key, val string) Fn
- func Props(p map[string]interface{}) Fn
- func Success(msg string) Fn
- func Tmpls(fps ...string) Fn
- func ToRoot() Fn
- func Unauthed() Fn
- func Url(u string) Fn
- func User(u interface{}) Fn
- func Vue(entry string) Fn
- func Warn(msg string) Fn
- type Responder
- func (doer Responder) CurrentUser(ctx context.Context) (interface{}, error)
- func (doer *Responder) Err(w http.ResponseWriter, r *http.Request, err error, opts ...Fn)
- func (doer *Responder) Html(w http.ResponseWriter, r *http.Request, opts ...Fn) error
- func (doer *Responder) Json(w http.ResponseWriter, r *http.Request, opts ...Fn) error
- func (doer *Responder) Redirect(w http.ResponseWriter, r *http.Request, opts ...Fn) error
- func (doer Responder) Session(ctx context.Context) (session.FlashSessionable, error)
- type ResponderOptFn
- type Response
Constants ¶
This section is empty.
Variables ¶
Functions ¶
func NoopResponderOptFn ¶
func NoopResponderOptFn(_ *Responder)
func WithAuthTemplate ¶
WithAuthTemplate sets the template identified by the filepath to use for rendering when a user is authenticated.
Authed requires this option.
func WithContactErrMsg ¶
WithContactErrMsg sets the error message to use for error Flashes.
We recommend using session.ContactUsErr as a template.
func WithCtxKeys ¶
func WithCtxKeys(keys ...ctx.CtxKeyable) func(*Responder)
WithCtxKeys appends the provided keys to be used for retrieving values from the *http.Request.Context.
WithCtxKeys deduplicates keys and filters out zero-value strings.
func WithLogger ¶
WithLogger sets the provided implementation of Logger in order to log all statements through it.
If no Logger is provided through this option, a defaultLogger will be configured.
func WithParser ¶
WithParser sets the provided implementation of template.Parser to use for parsing HTML templates.
func WithRootUrl ¶
WithRootUrl sets the provided URL after parsing it into a *url.URL to use for rendering and redirecting
NOTE: If u fails parsing by url.ParseRequestURI, the root URL becomes https://example.com
func WithSessionKey ¶
func WithSessionKey(key ctx.CtxKeyable) func(*Responder)
WithSessionKey sets the key to use for grabbing a session.Sessionable out of the *http.Request.Context
Responder.Session requires this option.
func WithUnauthTemplate ¶
WithUnauthTemplate sets the template identified by the filepath to use for rendering when a user is not authenticated.
Unauthed requires this option.
func WithUserSessionKey ¶
func WithUserSessionKey(key ctx.CtxKeyable) func(*Responder)
WithUserSessionKey sets the key to use for grabbing a user out of the session.Sessionable set in the *http.Request.Context
Responder.CurrentUser requires this option.
func WithVueTemplate ¶
WithVueTemplate sets the template identified by the filepath to use for rendering a Vue client application.
Vue requires this option.
Types ¶
type Fn ¶
A Fn is a functional option that mutates the state of the Response.
func Authed ¶
func Authed() Fn
Authed prepends all templates with the base authenticated template and adds resp.user from the session.
If no user can be retrieved from the session, it is assumed a user is not logged in and returns ErrNoUser.
If WithAuthTemplate was not called setting up the Responder, ErrBadConfig returns.
func Data ¶
Data merges the provided map with existing data. If a key already exists, it's value is overwritten.
Used with Responder.Html and Responder.Json. When used with Json, this data will populate the "data" key.
Prefer Props over Data when using with Vue if the map provided here is intended to be available for rendering the base Vue template.
func GenericErr ¶
GenericErr combines Err() and Flash() to log the passed in error and set a generic error flash in the session using either the string set by WithContactErrMsg or session.DefaultErrMsg.
func Props ¶
Props structures the provided data alongside default values.
Used with Responder.Html, specifically in conjunction with Vue. Accordingly, prefer this over Data when using Vue.
Here's the schema:
{ "initialProps": { "currentUser": r.user ...key-value pairs set by d.ctxKeys }, ...map set by p }
Props first passes p into Data. Then, Props passes a new "initialProps" map into Data then p.
It is not required to set any keys for pulling additional values out of the *http.Request.Context. Use WithCtxKeys to do so when applicable.
func Success ¶
Success sets the status OK to http.StatusOK and sets a session.FlashSuccess flash in the session with the passed in msg.
Used with Responder.Html.
func Unauthed ¶
func Unauthed() Fn
Unauthed prepends all templates with the base unauthenticated template. If the first template is the base authenticated template, this overwrites it.
If WithUnauthTemplate was not called setting up the Responder, ErrBadConfig returns.
func Url ¶
Url parses raw the URL string and sets it in the *Response if successful.
Used with Responder.Redirect.
func User ¶
func User(u interface{}) Fn
User stores the user in the *Response.
Used with Responder.Html and Responder.Json. When used with Json, the user is assigned to the "currentUser" key.
type Responder ¶
Responder maintains reusable pieces for responding to HTTP requests. It exposes many common methods for writing structured data as an HTTP response. These are the forms of response Responder can execute:
Html Json Redirect
Most oftentimes, setting up a single instance of a Responder suffices for an application. Meaning, one needs only application-wide configuration of how HTTP responses should look. Our suggestion does not exclude creating diverse Responders for non-overlapping segments of an application.
When handling a specific HTTP request, calling code supplies additional data, structure, and so forth through Fn functions. While one can create functions of the same type, the Responder and Response structs do not expose much - if anything - to interact with.
func NewResponder ¶
func NewResponder(opts ...ResponderOptFn) *Responder
NewResponder constructs a *Responder using the ResponderOptFns passed in.
TODO(dlk): make setting root url required arg? + cannot redirect in err state w/o
func (Responder) CurrentUser ¶
CurrentUser retrieves the user set in the context.
If WithUserSessionKey was not called setting up the Responder or the context.Context has no value for that key, ErrNotFound returns.
func (*Responder) Err ¶
Err wraps http.Error(), logging the error causing the failure state.
Use in exceptional circumstances when no Redirect or Html can occur.
func (*Responder) Html ¶
Html composes together HTML templates set in *Responder and configured by Authed, Unauthed, Tmpls and other such calls.
func (*Responder) Json ¶
Json responds with data in JSON format, collating it from User(), Data() and setting appropriate headers.
The JSON schema will look like this:
{ "currentUser": {}, "data": {} }
User() calls populate "currentUser" Data() calls populate "data"
func (*Responder) Redirect ¶
Redirect calls http.Redirect, given Url() set the redirect destination.
If Code() set the status code to something other than standard redirect 3xx statuses, Redirect overwrites the status code with an appropriate 3xx status code.
func (Responder) Session ¶
Session retrieves the session set in the context as a session.FlashSessionable.
session.FlashSessionable identifies the minimal functionality required for resp but could be swap out for a more expansive interface such as session.TrailsSessionable.
If WithSessionKey was not called setting up the Responder or the context.Context has no value for that key, ErrNotFound returns.
type ResponderOptFn ¶
type ResponderOptFn func(*Responder)
type Response ¶
type Response struct {
// contains filtered or unexported fields
}
A Response is the internal object a Responder response method builds while applying all functional options.
Notably, a Response holds a map[string]interface{} that stores data necessary for responding to the HTTP request.