Documentation
¶
Overview ¶
Package web extends the standard net/http pkg to provide a services framework.
Index ¶
- Constants
- Variables
- func Decode(r *http.Request, ptr interface{}) error
- func ErrsWrap(err error, new string) error
- func GetBoolCMap(c *cmap.ConcurrentMap, key string) *bool
- func GetInboundIP(r *http.Request) (string, error)
- func GetOutboundAddr() string
- func GetOutboundIP() string
- func GetStrCMap(c *cmap.ConcurrentMap, key string) *string
- func HTMLEntitiesToString(s string) string
- func Healthcheck(url string) error
- func IfModifiedSince(subject, since string) bool
- func IsShutdown(err error) bool
- func LastModified(x time.Time) string
- func NewCMap() cmap.ConcurrentMap
- func NewRequestError(err error, status int) error
- func NewShutdownError(message string) error
- func Nonce(size int) (string, error)
- func Params(r *http.Request) map[string]string
- func Redirect(ctx context.Context, w http.ResponseWriter, r *http.Request, url string, ...) error
- func Respond(ctx context.Context, w http.ResponseWriter, data interface{}, statusCode int) error
- func RespondError(ctx context.Context, w http.ResponseWriter, err error) error
- func RuneToHTMLEntity(entity rune) string
- func SetCMap(c *cmap.ConcurrentMap, key string, val interface{})
- func StringToHTMLEntities(s string) string
- type App
- type CSP
- type Cache
- type Error
- type ErrorResponse
- type FieldError
- type Handler
- type Middleware
- type Resource
- type RespStatus
- type Response
- type ResponseError
- type Values
Constants ¶
const ( JSON = "application/json" WEBMANIFEST = "application/manifest+json" GIF = "image/gif" ICON = "image/x-icon" JPG = "image/jpeg" PNG = "image/png" SVG = "image/svg+xml" //SVG = "application/xml" //... FAIL @ browser. //... CloudFront resets content-type to this if file's 1st line is HTML comment. WEBP = "image/webp" CSS = "text/css" HTML = "text/html" JS = "text/javascript" WOFF = "font/woff" BOGUS = "bogus" MALFORMED = "malformed" UNSUPPORTED = "unsupported" )
Content Types (MIME Types). https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
const Key1 ctxKey = 1
Key1 is used for protected set/get of Claims VALUEs from a `context.Context`.
const RespTimeMax = 9000
RespTimeMax is app-wide max response time in milliseconds, measured from time of request arriving at its (first) endpoint handler; first in the middlewares chain.
Variables ¶
var RespondFoo = NewResponse(CSP{ ConnectSrc: []string{ "https://foo.foo", }, ScriptSrc: []string{ "https://foo.foo", }, StyleSrc: []string{ "'unsafe-inline'", "https://foo.foo", }, DefaultSrc: []string{ "https://foo.foo", }, })
RespondFoo is a Response function that loosens Content Security Policy (CSP) to allow connections, scripts and such, each from a whitelist of sources. USE THIS AS A TEMPLATE to declare custom response function(s), e.g., per service.
Functions ¶
func Decode ¶
Decode reads the body of an HTTP request (r) looking for a JSON document. The body is decoded (unmarshalled) into the provided pointer (ptr). If pointing to a struct, then validator operates against its field tags.
func GetBoolCMap ¶
func GetBoolCMap(c *cmap.ConcurrentMap, key string) *bool
GetBoolCMap (`*bool`) per `key`
func GetInboundIP ¶
GetInboundIP from X-REAL-IP > X-FORWARDED-FOR > r.RemoteAddr https://golangbyexample.com/golang-ip-address-http-request/
func GetOutboundAddr ¶
func GetOutboundAddr() string
GetOutboundAddr returns the preferred outbound ip address of this machine
func GetOutboundIP ¶
func GetOutboundIP() string
GetOutboundIP returns the preferred outbound ip address of this machine
func GetStrCMap ¶
func GetStrCMap(c *cmap.ConcurrentMap, key string) *string
GetStrCMap (`*string`) per `key`
func HTMLEntitiesToString ¶
HTMLEntitiesToString ... works @ SUBSET; NOT ALL Unicode; unknown (HTML Entities) remain UNAFFECTED.
HTMLEntitiesToString( "“Freddie's Diner” ☧ <bogus@email.addr>" )
=>“Freddie's Diner” ☧ <bogus@email.addr>
func Healthcheck ¶
Healthcheck to satisfy Docker healthcheck of any service endpoint without requiring any externals; neither (GNU) utilities nor shell.
func IfModifiedSince ¶
IfModifiedSince is a header-helper function that tests if `subject` is modified `since`. Returns `true` is `subject` is newer than `since`. Returns `true` on either parse error. Time-string format is that of such headers (RFC1123):
"Thu, 20 Aug 2020 18:26:03 GMT"
func IsShutdown ¶
IsShutdown checks to see if the shutdown error is contained in the specified error value.
func LastModified ¶
LastModified is a header-helper function that returns the properly formatted value to fit the HTTP "Last-Modified: <LastModified>" header: `Thu, 20 Aug 2020 18:26:03 GMT`.
Usage: w.Header().Set("Last-Modified", LastModified(time.Now().UTC()))
func NewRequestError ¶
NewRequestError wraps a provided error with an HTTP status code. The web framework prints this to service log and sends as response (JSON). This function should be used when handlers encounter expected errors.
func NewShutdownError ¶
NewShutdownError returns an error that causes the framework to signal a graceful shutdown.
func Redirect ¶
func Redirect(ctx context.Context, w http.ResponseWriter, r *http.Request, url string, code int, msg ...string) error
Redirect performs as http.Redirect(..), while fitting the context-based signature of this library.
func RespondError ¶
RespondError is the nominal RespondError function; enforces strictest CSP.
func RuneToHTMLEntity ¶
RuneToHTMLEntity https://gist.github.com/brandonrachal/10605780 RuneToHTMLEntity('𝓢') // d4e2;
func SetCMap ¶
func SetCMap(c *cmap.ConcurrentMap, key string, val interface{})
SetCMap any type per `key`
func StringToHTMLEntities ¶
StringToHTMLEntities ... StringToHTMLEntities("𝓢 foo") // d4e2; foo
Types ¶
type App ¶
type App struct {
// contains filtered or unexported fields
}
App is the entrypoint into our app and what configures our context object for http handlers. Add any configuration data/logic here.
func NewApp ¶
func NewApp(shutdown chan os.Signal, mw ...Middleware) *App
NewApp creates an `App` value to handle a set of routes for the application.
func (*App) Handle ¶
func (a *App) Handle(method string, path string, handler Handler, mw ...Middleware)
Handle sets a handler function for a given HTTP method-path pair to the application server mux.
func (*App) HandleDebug ¶
func (a *App) HandleDebug(method string, path string, handler Handler, mw ...Middleware)
HandleDebug sets a handler function for a given HTTP method-path pair to the default http package server mux. /debug is added to the path.
func (*App) ServeHTTP ¶
func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements the `http.Handler` interface. It's the entry point for all http traffic and allows the opentelemetry mux to run first to handle tracing. The opentelemetry mux then calls the application mux to handle application traffic.
func (*App) SignalShutdown ¶
func (a *App) SignalShutdown()
SignalShutdown is used to gracefully shutdown the app when an integrity issue is identified.
type CSP ¶
type CSP struct {
ConnectSrc, ScriptSrc, StyleSrc, FrameSrc, FontSrc, ImgSrc, ObjectSrc, DefaultSrc []string
}
CSP contains lists of Content Security Policy (CSP) sources.
type Cache ¶
type Cache cmap.ConcurrentMap
Cache ...
func (*Cache) GetResource ¶
GetResource (`*Resource`) per `key`. Return zero-value if `!ok`.
type Error ¶
type Error struct { Err error Status int Fields []FieldError }
Error is used to pass an error during the request through the application with web specific context.
type ErrorResponse ¶
type ErrorResponse struct { Error string `json:"error"` Fields []FieldError `json:"fields,omitempty"` }
ErrorResponse is the form used for API responses from failures in the API.
type FieldError ¶
FieldError is used to indicate an error with a specific request field.
type Handler ¶
Handler defines the per-request endpoint-handler type for this app framework. ... which BREAKS (???) the standard lib's `Handler` INTERFACE:
type Handler interface { ServeHTTP(ResponseWriter, *Request) }
type Middleware ¶
Middleware is a function designed to run some code before and/or after another Handler. It is designed to remove boilerplate or other concerns not direct to any given Handler.
type Resource ¶
type Resource struct { Key string Content []byte Ctype string Etag string SRI string Ext string Mtime time.Time Ctime time.Time Model bool Gz bool Err error Code int }
Resource contains all the parameters of a web-server resource.
func GetResourceCMap ¶
func GetResourceCMap(c *cmap.ConcurrentMap, key string) *Resource
GetResourceCMap (`*Resource`) per `key`
type RespStatus ¶
RespStatus contains code and text of an HTTP response.
func Status ¶
func Status(status int) RespStatus
Status returns RespStatus of an HTTP response code.
type Response ¶
Response is the per-request HTTP response function.
func NewResponse ¶
NewResponse closes over CSP sources (whitelists), returning a Response function.
type ResponseError ¶
ResponseError is the per-request HTTP response function for errors.
func NewResponseError ¶
func NewResponseError(csp CSP) ResponseError
NewResponseError closes over CSP sources (whitelists), returning a ResponseError function.