web

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 10, 2022 License: Unlicense Imports: 27 Imported by: 0

Documentation

Overview

Package web extends the standard net/http pkg to provide a services framework.

Index

Constants

View Source
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

View Source
const Key1 ctxKey = 1

Key1 is used for protected set/get of Claims VALUEs from a `context.Context`.

View Source
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

View Source
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

func Decode(r *http.Request, ptr interface{}) error

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 ErrsWrap

func ErrsWrap(err error, new string) error

ErrsWrap safely wraps error (err) regardless if nil.

func GetBoolCMap

func GetBoolCMap(c *cmap.ConcurrentMap, key string) *bool

GetBoolCMap (`*bool`) per `key`

func GetInboundIP

func GetInboundIP(r *http.Request) (string, error)

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

func HTMLEntitiesToString(s string) string

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

func Healthcheck(url string) error

Healthcheck to satisfy Docker healthcheck of any service endpoint without requiring any externals; neither (GNU) utilities nor shell.

func IfModifiedSince

func IfModifiedSince(subject, since string) bool

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

func IsShutdown(err error) bool

IsShutdown checks to see if the shutdown error is contained in the specified error value.

func LastModified

func LastModified(x time.Time) string

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 NewCMap

func NewCMap() cmap.ConcurrentMap

NewCMap returns an embedded k-v store (`Cache`).

func NewRequestError

func NewRequestError(err error, status int) error

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

func NewShutdownError(message string) error

NewShutdownError returns an error that causes the framework to signal a graceful shutdown.

func Nonce

func Nonce(size int) (string, error)

Nonce of size bytes as a URL-encoded string.

func Params

func Params(r *http.Request) map[string]string

Params returns the web call parameters from the request.

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 Respond

func Respond(ctx context.Context, w http.ResponseWriter, data interface{}, statusCode int) error

Respond is the nominal Response function; enforces strictest CSP.

func RespondError

func RespondError(ctx context.Context, w http.ResponseWriter, err error) error

RespondError is the nominal RespondError function; enforces strictest CSP.

func RuneToHTMLEntity

func RuneToHTMLEntity(entity rune) string

RuneToHTMLEntity https://gist.github.com/brandonrachal/10605780 RuneToHTMLEntity('𝓢') // &#1d4e2;

func SetCMap

func SetCMap(c *cmap.ConcurrentMap, key string, val interface{})

SetCMap any type per `key`

func StringToHTMLEntities

func StringToHTMLEntities(s string) string

StringToHTMLEntities ... StringToHTMLEntities("𝓢 foo") // &#1d4e2; 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 NewCache

func NewCache() Cache

NewCache returns an embedded k-v store (`Cache`).

func (*Cache) GetResource

func (c *Cache) GetResource(key string) *Resource

GetResource (`*Resource`) per `key`. Return zero-value if `!ok`.

func (*Cache) GetStr

func (c *Cache) GetStr(key string) *string

GetStr (`*string`) per `key`. Return zero-value if `!ok`.

func (*Cache) Set

func (c *Cache) Set(key string, val interface{})

Set any type `val` per `key`

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.

func (*Error) Error

func (err *Error) Error() string

Error implements the error interface. It uses the default message of the wrapped error. This is what will be shown in the services' logs.

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

type FieldError struct {
	Field string `json:"field"`
	Error string `json:"error"`
}

FieldError is used to indicate an error with a specific request field.

type Handler

type Handler func(ctx context.Context, w http.ResponseWriter, r *http.Request) error

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

type Middleware func(Handler) Handler

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

type RespStatus struct {
	Code int    `json:"code"`
	Text string `json:"text"`
}

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

type Response func(context.Context, http.ResponseWriter, interface{}, int) error

Response is the per-request HTTP response function.

func NewResponse

func NewResponse(cc CSP) Response

NewResponse closes over CSP sources (whitelists), returning a Response function.

type ResponseError

type ResponseError func(context.Context, http.ResponseWriter, error) error

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.

type Values

type Values struct {
	TraceID    string
	Now        time.Time
	StatusCode int
}

Values represent state for each request.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL