httputil

package
v0.0.0-...-6d3478e Latest Latest
Warning

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

Go to latest
Published: Jan 16, 2018 License: MIT Imports: 33 Imported by: 0

Documentation

Index

Constants

View Source
const (
	TwentyFourHours   = 86400
	FourthyEightHours = 2 * TwentyFourHours

	TwentyFourHoursDuration   = TwentyFourHours * time.Second
	FourthyEightHoursDuration = TwentyFourHoursDuration * 2
)

Time constants

View Source
const (
	CONNECT = "CONNECT"
	DELETE  = "DELETE"
	GET     = "GET"
	HEAD    = "HEAD"
	OPTIONS = "OPTIONS"
	PATCH   = "PATCH"
	POST    = "POST"
	PUT     = "PUT"
	TRACE   = "TRACE"
)

HTTP methods

View Source
const (
	MIMEApplicationJSON                  = "application/json"
	MIMEApplicationJSONCharsetUTF8       = MIMEApplicationJSON + "; " + charsetUTF8
	MIMEApplicationJavaScript            = "application/javascript"
	MIMEApplicationJavaScriptCharsetUTF8 = MIMEApplicationJavaScript + "; " + charsetUTF8
	MIMEApplicationXML                   = "application/xml"
	MIMEApplicationXMLCharsetUTF8        = MIMEApplicationXML + "; " + charsetUTF8
	MIMETextXML                          = "text/xml"
	MIMETextXMLCharsetUTF8               = MIMETextXML + "; " + charsetUTF8
	MIMEApplicationForm                  = "application/x-www-form-urlencoded"
	MIMEApplicationProtobuf              = "application/protobuf"
	MIMEApplicationMsgpack               = "application/msgpack"
	MIMETextHTML                         = "text/html"
	MIMETextHTMLCharsetUTF8              = MIMETextHTML + "; " + charsetUTF8
	MIMETextPlain                        = "text/plain"
	MIMETextPlainCharsetUTF8             = MIMETextPlain + "; " + charsetUTF8
	MIMEMultipartForm                    = "multipart/form-data"
	MIMEOctetStream                      = "application/octet-stream"
)

MIME types

View Source
const (
	HeaderAccept              = "Accept"
	HeaderAcceptEncoding      = "Accept-Encoding"
	HeaderAllow               = "Allow"
	HeaderAuthorization       = "Authorization"
	HeaderContentDisposition  = "Content-Disposition"
	HeaderContentEncoding     = "Content-Encoding"
	HeaderContentLength       = "Content-Length"
	HeaderContentType         = "Content-Type"
	HeaderCookie              = "Cookie"
	HeaderSetCookie           = "Set-Cookie"
	HeaderIfModifiedSince     = "If-Modified-Since"
	HeaderLastModified        = "Last-Modified"
	HeaderLocation            = "Location"
	HeaderUpgrade             = "Upgrade"
	HeaderVary                = "Vary"
	HeaderWWWAuthenticate     = "WWW-Authenticate"
	HeaderXForwardedFor       = "X-Forwarded-For"
	HeaderXForwardedProto     = "X-Forwarded-Proto"
	HeaderXForwardedProtocol  = "X-Forwarded-Protocol"
	HeaderXForwardedSsl       = "X-Forwarded-Ssl"
	HeaderXUrlScheme          = "X-Url-Scheme"
	HeaderXHTTPMethodOverride = "X-HTTP-Method-Override"
	HeaderXRealIP             = "X-Real-IP"
	HeaderXRequestID          = "X-Request-ID"
	HeaderServer              = "Server"
	HeaderOrigin              = "Origin"

	// Access control
	HeaderAccessControlRequestMethod    = "Access-Control-Request-Method"
	HeaderAccessControlRequestHeaders   = "Access-Control-Request-Headers"
	HeaderAccessControlAllowOrigin      = "Access-Control-Allow-Origin"
	HeaderAccessControlAllowMethods     = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowHeaders     = "Access-Control-Allow-Headers"
	HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials"
	HeaderAccessControlExposeHeaders    = "Access-Control-Expose-Headers"
	HeaderAccessControlMaxAge           = "Access-Control-Max-Age"

	// Security
	HeaderStrictTransportSecurity = "Strict-Transport-Security"
	HeaderXContentTypeOptions     = "X-Content-Type-Options"
	HeaderXXSSProtection          = "X-XSS-Protection"
	HeaderXFrameOptions           = "X-Frame-Options"
	HeaderContentSecurityPolicy   = "Content-Security-Policy"
	HeaderXCSRFToken              = "X-CSRF-Token"
)

Headers

View Source
const (

	// MultipartKey defines the key used to store multipart Form.
	MultipartKey = "MultiPartForm"
)

Variables

View Source
var ErrInvalidRedirectCode = errors.New("Invalid redirect code")

ErrInvalidRedirectCode is error returned when redirect code is wrong.

View Source
var (
	ErrNoPush = errors.New("Push Not Supported")
)

errors ...

View Source
var ErrNoRenderInitiated = errors.New("Renderer was not set or is uninitiated")

ErrNoRenderInitiated defines the error returned when a renderer is not set but Context.Render() is called.

Functions

func BadRequest

func BadRequest(ctx *Context) error

BadRequest implements a Handler which returns http.StatusBagRequest always.

func BadRequestWithError

func BadRequestWithError(err error, ctx *Context) error

BadRequestWithError implements a Handler which returns http.StatusBagRequest always.

func ErrorMessage

func ErrorMessage(status int, header string, err error) string

ErrorMessage returns a string which contains a json value of a given error message to be delivered.

func GetFileMimeType

func GetFileMimeType(path string) string

GetFileMimeType returns associated mime type for giving file extension.

func GorillaMuxVars

func GorillaMuxVars(ctx *Context) error

GorillaMuxVars retrieves the parameter lists from the underline variable map provided by the gorilla mux router and stores those into the context.

func GzipServer

func GzipServer(fs filesystem.FileSystem, gzipped bool, mw ...Middleware) http.Handler

GzipServer returns a http.Handler which handles the necessary bits to gzip or ungzip file resonses from a http.FileSystem.

func HTMLContextFunctions

func HTMLContextFunctions(c *Context) htemplate.FuncMap

HTMLContextFunctions returns a map of tempalte funcs for usage with text/template.Template.

func HTTPFunc

func HTTPFunc(nx Handler, befores ...func()) http.HandlerFunc

HTTPFunc returns a http.HandleFunc which wraps the Handler for usage with a server.

func HTTPGzipServer

func HTTPGzipServer(fs http.FileSystem, gzipped bool, mw ...Middleware) http.Handler

HTTPGzipServer returns a http.Handler which handles the necessary bits to gzip or ungzip file resonses from a http.FileSystem.

func HandlerFuncToHandler

func HandlerFuncToHandler(hl http.HandlerFunc) http.Handler

HandlerFuncToHandler defines a function which returns a http.Handler from the provided http.HandlerFunc.

func IdentityHandler

func IdentityHandler(c *Context) error

IdentityHandler defines a Handler function that returns a nil error.

func LetsEncryptTLS

func LetsEncryptTLS(http2 bool) (*autocert.Manager, *tls.Config)

LetsEncryptTLS returns a tls.Config instance which retrieves its its tls certificate from LetsEncrypt service.

func LoadTLS

func LoadTLS(cert, key string) (*tls.Config, error)

LoadTLS loads a tls.Config from a key and cert file path

func NetworkAuthenticationNeeded

func NetworkAuthenticationNeeded(ctx *Context) error

NetworkAuthenticationNeeded implements a Handler which returns http.StatusNetworkAuthenticationRequired always.

func NoContentRequest

func NoContentRequest(ctx *Context) error

NoContentRequest implements a Handler which returns http.StatusNoContent always.

func NotFound

func NotFound(ctx *Context) error

NotFound implements a Handler which returns http.StatusNotFound always.

func OKRequest

func OKRequest(ctx *Context) error

OKRequest implements a Handler which returns http.StatusOK always.

func Params

func Params(ctx bag.ValueBag, r *http.Request, multipartFormSize int64) error

Params defines a function to return all parameter values and query values retrieved from the request.

func ParseAuthorization

func ParseAuthorization(val string) (authType string, token string, err error)

ParseAuthorization returns the scheme and token of the Authorization string if it's valid.

func ParseTokens

func ParseTokens(val string) ([]string, error)

ParseTokens parses the base64 encoded token sent as part of the Authorization string, It expects all parts of string to be seperated with ':', returning splitted slice.

func ServeHandler

func ServeHandler(h Handler) http.Handler

ServeHandler returns a http.Handler which serves request to the provided Handler.

func TextContextFunctions

func TextContextFunctions(c *Context) template.FuncMap

TextContextFunctions returns a map of tempalte funcs for usage with text/template.Template.

func WaitOnInterrupt

func WaitOnInterrupt(cbs ...func())

WaitOnInterrupt will register the needed signals to wait until it recieves a os interrupt singnal and calls any provided functions later.

func WriteErrorMessage

func WriteErrorMessage(w http.ResponseWriter, status int, header string, err error)

WriteErrorMessage writes the giving error message to the provided writer.

Types

type Context

type Context struct {
	bag.ValueBag
	// contains filtered or unexported fields
}

Context defines a http related context object for a request session which is to be served.

func Apply

func Apply(c *Context, ops ...Options) *Context

Apply applies giving options against Context instance returning context again.

func NewContext

func NewContext(ops ...Options) *Context

NewContext returns a new Context with the Options slice applied.

func (*Context) AddHeader

func (c *Context) AddHeader(key string, value string)

AddHeader adds te value into the giving key into the response object header.

func (*Context) Attachment

func (c *Context) Attachment(file, name string) (err error)

Attachment attempts to attach giving file details.

func (*Context) Bag

func (c *Context) Bag() bag.ValueBag

Bag returns the underline value bag DEPRECATED: This is added to provided backward compatiblity.

func (*Context) Blob

func (c *Context) Blob(code int, contentType string, b []byte) (err error)

Blob write giving byte slice as response with proper mime type.

func (*Context) Body

func (c *Context) Body() io.ReadCloser

Body returns the associated io.ReadCloser which is the body of the Request.

func (*Context) ClearFlash

func (c *Context) ClearFlash(name string)

ClearFlash removes all available message items from the context flash message map.

func (*Context) ClearFlashMessages

func (c *Context) ClearFlashMessages()

ClearFlashMessages clears all available message items within the flash map.

func (*Context) Context

func (c *Context) Context() context.Context

Context returns the underline context.Context for the request.

func (*Context) Cookie

func (c *Context) Cookie(name string) (*http.Cookie, error)

Cookie returns the associated cookie by the giving name.

func (*Context) Cookies

func (c *Context) Cookies() []*http.Cookie

Cookies returns the associated cookies slice of the http request.

func (*Context) Error

func (c *Context) Error(code int, err error, message string) error

Error renders giving error response into response.

func (*Context) File

func (c *Context) File(file string) (err error)

File streams file content into response.

func (*Context) Flash

func (c *Context) Flash(name string) []string

Flash returns an associated slice of messages/string, for giving flash name/key.

func (*Context) FlashMessages

func (c *Context) FlashMessages() map[string][]string

FlashMessages returns available map of all flash messages. A copy is sent not the context currently used instance.

func (*Context) FormFile

func (c *Context) FormFile(name string) (*multipart.FileHeader, error)

FormFile returns the giving FileHeader for the giving name.

func (*Context) FormParams

func (c *Context) FormParams() (url.Values, error)

FormParams returns a url.Values which contains the parse form values for multipart or wwww-urlencoded forms.

func (*Context) FormValue

func (c *Context) FormValue(name string) string

FormValue returns the value of the giving item from the form fields.

func (*Context) GetHeader

func (c *Context) GetHeader(key string) string

GetHeader returns associated value of key from request headers.

func (*Context) HTML

func (c *Context) HTML(code int, html string) (err error)

HTML renders giving html into response.

func (*Context) HTMLBlob

func (c *Context) HTMLBlob(code int, b []byte) (err error)

HTMLBlob renders giving html into response.

func (*Context) HTMLTemplate

func (c *Context) HTMLTemplate(code int, tmpl *htemplate.Template, data interface{}) error

HTMLTemplate renders provided template.Template object into the response object.

func (*Context) HasHeader

func (c *Context) HasHeader(key string, value string) bool

HasHeader returns true/false if string.Contains validate giving header key has value within string of the request header. if value is an empty string, then method only validates that you have key in headers.

func (*Context) Header

func (c *Context) Header() http.Header

Header returns the header associated with the giving request.

func (*Context) ID

func (c *Context) ID() string

ID returns the unique id of giving request context.

func (*Context) InitForms

func (c *Context) InitForms() error

InitForms will call the appropriate function to parse the necessary form values within the giving request context.

func (*Context) Inline

func (c *Context) Inline(file, name string) (err error)

Inline attempts to inline file content.

func (*Context) IsTLS

func (c *Context) IsTLS() bool

IsTLS returns true/false if the giving reqest is a tls connection.

func (*Context) IsWebSocket

func (c *Context) IsWebSocket() bool

IsWebSocket returns true/false if the giving reqest is a websocket connection.

func (*Context) JSON

func (c *Context) JSON(code int, i interface{}) (err error)

JSON renders giving json data into response.

func (*Context) JSONBlob

func (c *Context) JSONBlob(code int, b []byte) (err error)

JSONBlob renders giving json data into response with proper mime type.

func (*Context) JSONP

func (c *Context) JSONP(code int, callback string, i interface{}) (err error)

JSONP renders giving jsonp as response with proper mime type.

func (*Context) JSONPBlob

func (c *Context) JSONPBlob(code int, callback string, b []byte) (err error)

JSONPBlob renders giving jsonp as response with proper mime type.

func (*Context) JSONPretty

func (c *Context) JSONPretty(code int, i interface{}, indent string) (err error)

JSONPretty renders giving json data as indented into response.

func (*Context) Metrics

func (c *Context) Metrics() metrics.Metrics

Metrics returns metric logger for giving context.

func (*Context) MultipartForm

func (c *Context) MultipartForm() (*multipart.Form, error)

MultipartForm returns the multipart form of the giving request if its a multipart request.

func (*Context) NoContent

func (c *Context) NoContent(code int) error

NoContent writes status code without writing content to response.

func (*Context) NotFound

func (c *Context) NotFound() error

NotFound writes calls the giving response against the NotFound handler if present, else uses a http.StatusMovedPermanently status code.

func (*Context) Path

func (c *Context) Path() string

Path returns the request path associated with the context.

func (*Context) QueryParam

func (c *Context) QueryParam(name string) string

QueryParam finds the giving value for the giving name in the querie set.

func (*Context) QueryParams

func (c *Context) QueryParams() url.Values

QueryParams returns the context url.Values object.

func (*Context) QueryString

func (c *Context) QueryString() string

QueryString returns the raw query portion of the request path.

func (*Context) RealIP

func (c *Context) RealIP() string

RealIP attempts to return the ip of the giving request.

func (*Context) Redirect

func (c *Context) Redirect(code int, url string) error

Redirect redirects context response.

func (*Context) Render

func (c *Context) Render(code int, tmpl string, data interface{}) (err error)

Render renders the giving string with data binding using the provided Render of the context.

func (*Context) Request

func (c *Context) Request() *http.Request

Request returns the associated request.

func (*Context) Reset

func (c *Context) Reset(r *http.Request, w http.ResponseWriter)

Reset resets context internal fields

func (*Context) Response

func (c *Context) Response() *Response

Response returns the associated response object for this context.

func (*Context) Scheme

func (c *Context) Scheme() string

Scheme attempts to return the exact url scheme of the request.

func (*Context) SetCookie

func (c *Context) SetCookie(cookie *http.Cookie)

SetCookie sets the cookie into the response object.

func (*Context) SetFlash

func (c *Context) SetFlash(name string, message string)

SetFlash sets giving message/messages into the slice bucket of the given name list.

func (*Context) SetHeader

func (c *Context) SetHeader(key string, value string)

SetHeader sets te key-value pair into the response object header.

func (*Context) Status

func (c *Context) Status(code int)

Status writes status code without writing content to response.

func (*Context) Stream

func (c *Context) Stream(code int, contentType string, r io.Reader) (err error)

Stream copies giving io.Readers content into response.

func (*Context) String

func (c *Context) String(code int, s string) (err error)

String renders giving string into response.

func (*Context) Template

func (c *Context) Template(code int, tmpl *template.Template, data interface{}) error

Template renders provided template.Template object into the response object.

func (*Context) XML

func (c *Context) XML(code int, i interface{}) (err error)

XML renders giving xml as response with proper mime type.

func (*Context) XMLBlob

func (c *Context) XMLBlob(code int, b []byte) (err error)

XMLBlob renders giving xml as response with proper mime type.

func (*Context) XMLPretty

func (c *Context) XMLPretty(code int, i interface{}, indent string) (err error)

XMLPretty renders giving xml as indent as response with proper mime type.

type ErrConditions

type ErrConditions interface {
	Match(error) bool
	Handle(*Context) error
}

ErrConditions defines a condition which matches expected error for performing giving action.

type ErrorCondition

type ErrorCondition struct {
	Err error
	Fn  Handler
}

ErrorCondition defines a type which sets the error that occurs and the handler to be called for such an error.

func ErrCondition

func ErrCondition(err error, fn Handler) ErrorCondition

ErrCondition returns ErrConditon using provided arguments.

func (ErrorCondition) Handler

func (ec ErrorCondition) Handler(ctx *Context) error

Handler calls the internal Handler with provided Context returning error.

func (ErrorCondition) Match

func (ec ErrorCondition) Match(err error) bool

Match validates the provided error matches expected error.

type ErrorHandler

type ErrorHandler func(error, *Context) error

ErrorHandler defines a function type which sets giving respnse to a Response object.

type FnErrorCondition

type FnErrorCondition struct {
	Fn  Handler
	Err func(error) bool
}

FnErrorCondition defines a type which sets the error that occurs and the handler to be called for such an error.

func FnErrCondition

func FnErrCondition(err func(error) bool, fn Handler) FnErrorCondition

FnErrCondition returns ErrConditon using provided arguments.

func (FnErrorCondition) Handler

func (ec FnErrorCondition) Handler(ctx *Context) error

Handler calls the internal Handler with provided Context returning error.

func (FnErrorCondition) Match

func (ec FnErrorCondition) Match(err error) bool

Match validates the provided error matches expected error.

type HTTPError

type HTTPError struct {
	Code int
	Err  error
}

HTTPError defines custom error that can be used to specify status code and message.

func (HTTPError) Error

func (h HTTPError) Error() string

Error returns error string. Implements error interface.

type Handler

type Handler func(*Context) error

Handler defines a function type to process a giving request.

func ErrorsAsResponse

func ErrorsAsResponse(code int, next Handler) Handler

ErrorsAsResponse returns a Handler which will always write out any error that occurs as the response for a request if any occurs.

func GorillaMW

func GorillaMW(next Handler) Handler

GorillaMW returns a middleware which wraps the next handler with the GorillaMuxVars.

func GorillaMuxHandler

func GorillaMuxHandler(next Handler) Handler

GorillaMuxHandler returns a Handler which handles the underline retrieval of parameters using gorilla mux router.

func GzipServe

func GzipServe(fs filesystem.FileSystem, gzipped bool) Handler

GzipServe returns a Handler which handles the necessary bits to gzip or ungzip file resonses from a http.FileSystem.

func HTTPConditionErrorFunc

func HTTPConditionErrorFunc(condition Handler, noerrorAction Handler, errorAction ErrorHandler) Handler

HTTPConditionErrorFunc returns a handler where a condition Handler is called whoes result if with an error is passed to the errorAction for execution else using the noerrorAction. Differs from HTTPConditionFunc due to the assess to the error value.

func HTTPConditionFunc

func HTTPConditionFunc(condition Handler, noerrorAction, errorAction Handler) Handler

HTTPConditionFunc retusn a handler where a Handler is used as a condition where if the handler returns an error then the errorAction is called else the noerrorAction gets called with context. This allows you create a binary switch where the final action is based on the success of the first. Generally if you wish to pass info around, use the context.Bag() to do so.

func HTTPConditionsFunc

func HTTPConditionsFunc(condition Handler, noerrAction Handler, errCons ...ErrConditions) Handler

HTTPConditionsFunc returns a Handler where if an error occurs would match the returned error with a Handler to be runned if the match is found.

func HTTPGzipServe

func HTTPGzipServe(fs http.FileSystem, gzipped bool) Handler

HTTPGzipServe returns a Handler which handles the necessary bits to gzip or ungzip file resonses from a http.FileSystem.

func HTTPRedirect

func HTTPRedirect(to string, code int) Handler

HTTPRedirect returns a Handler which always redirect to the given path.

func IdentityMW

func IdentityMW(next Handler) Handler

IdentityMW defines a Handler function that returns a the next Handler passed to it.

func LogMW

func LogMW(next Handler) Handler

LogMW defines a log middleware function which wraps a Handler and logs what request and response was sent incoming.

func MW

func MW(mos ...Middleware) Handler

MW combines multiple Middleware to return a single Handler.

func MuxHandler

func MuxHandler(errHandler ErrorHandler, handle Handler, mw ...Middleware) Handler

MuxHandler defines a function which will return a Handler which will be used to handle a request.

func OnDone

func OnDone(condition Handler, nexts ...Handler) Handler

OnDone calls the next Handler after the condition handler returns without error.

func OnError

func OnError(condition Handler, errorAction Handler) Handler

OnError calls the next Handler after the condition handler returns an error.

func OnErrorAccess

func OnErrorAccess(condition Handler, errorAction ErrorHandler) Handler

OnErrorAccess calls the next ErrorHandler after the condition handler returns an error.

func OnNoError

func OnNoError(condition Handler, action Handler) Handler

OnNoError calls the next Handler after the condition handler returns no error.

func WrapHandler

func WrapHandler(fx http.HandlerFunc) Handler

WrapHandler attempts to wrap provided http.HandlerFunc to return a httputil.Context.

type HandlerFuncMW

type HandlerFuncMW func(Handler, ...Middleware) http.HandlerFunc

HandlerFuncMW defines a function which wraps a provided http.handlerFunc which encapsulates the original for a underline operation.

type HandlerMW

type HandlerMW func(Handler, ...Middleware) Handler

HandlerMW defines a function which wraps a provided http.handlerFunc which encapsulates the original for a underline operation.

type Middleware

type Middleware func(next Handler) Handler

Middleware defines a function type which is used to create a chain of handlers for processing giving request.

func DMW

func DMW(mo, mi Middleware) Middleware

DMW combines two middleware and returns a single Handler.

func MWi

func MWi(mos ...Middleware) Middleware

MWi combines multiple Middleware to return a new Middleware.

func MetricsMW

func MetricsMW(m metrics.Metrics) Middleware

MetricsMW defines a MW function that adds giving metrics.Metric to all context before calling next handler.

func StripPrefixMW

func StripPrefixMW(prefix string) Middleware

StripPrefixMW returns a middleware which strips the URI of the request of the provided Prefix. All prefix must come in /prefix/ format.

type Options

type Options func(*Context)

Options defines a function type which receives a Context pointer and sets/modifiers it's internal state values.

func SetID

func SetID(id string) Options

SetID sets the id of the giving context.

func SetMetrics

func SetMetrics(r metrics.Metrics) Options

SetMetrics returns a Option to sets the giving Metrics object for logging into the provided context.

func SetNotFound

func SetNotFound(r Handler) Options

SetNotFound will return a function to set the NotFound handler for a giving context.

func SetPath

func SetPath(p string) Options

SetPath sets the path of the giving context.

func SetRenderer

func SetRenderer(r Render) Options

SetRenderer will returns a function to set the render used by a giving context.

func SetRequest

func SetRequest(r *http.Request) Options

SetRequest returns a option function to set the request of a Context.

func SetResponse

func SetResponse(r *Response) Options

SetResponse returns a option function to set the response of a Context.

func SetResponseWriter

func SetResponseWriter(w http.ResponseWriter, befores ...func()) Options

SetResponseWriter returns a option function to set the response of a Context.

func SetValueBag

func SetValueBag(vbag bag.ValueBag) Options

SetValueBag sets the ValueBag of the giving context.

type Render

type Render interface {
	Render(io.Writer, string, interface{}) error
}

Render defines a giving type which exposes a Render method for rendering a custom output from a provided input string and bind object.

type Response

type Response struct {
	Writer    http.ResponseWriter
	Status    int
	Size      int64
	Committed bool
	// contains filtered or unexported fields
}

Response wraps an http.ResponseWriter and implements its interface to be used by an HTTP handler to construct an HTTP response. See: https://golang.org/pkg/net/http/#ResponseWriter

func (*Response) After

func (r *Response) After(fn func())

After adds the giving function into a response after list.

func (*Response) Before

func (r *Response) Before(fn func())

Before adds the giving function into a response before list.

func (*Response) CloseNotify

func (r *Response) CloseNotify() <-chan bool

CloseNotify implements the http.CloseNotifier interface to allow detecting when the underlying connection has gone away. This mechanism can be used to cancel long operations on the server if the client has disconnected before the response is ready. See http.CloseNotifier(https://golang.org/pkg/net/http/#CloseNotifier)

func (*Response) Flush

func (r *Response) Flush()

Flush implements the http.Flusher interface to allow an HTTP handler to flush buffered data to the client. See http.Flusher(https://golang.org/pkg/net/http/#Flusher)

func (*Response) Header

func (r *Response) Header() http.Header

Header returns the header map for the writer that will be sent by WriteHeader. Changing the header after a call to WriteHeader (or Write) has no effect unless the modified headers were declared as trailers by setting the "Trailer" header before the call to WriteHeader (see example) To suppress implicit response headers, set their value to nil. Example: https://golang.org/pkg/net/http/#example_ResponseWriter_trailers

func (*Response) Hijack

func (r *Response) Hijack() (net.Conn, *bufio.ReadWriter, error)

Hijack implements the http.Hijacker interface to allow an HTTP handler to take over the connection. See http.Hijacker(https://golang.org/pkg/net/http/#Hijacker)

func (*Response) Push

func (r *Response) Push(target string, ops *http.PushOptions) error

Push adds support for http.Pusher, if available and lets you push resources.

func (*Response) Write

func (r *Response) Write(b []byte) (n int, err error)

Write writes the data to the connection as part of an HTTP reply.

func (*Response) WriteHeader

func (r *Response) WriteHeader(code int)

WriteHeader sends an HTTP response header with status code. If WriteHeader is not called explicitly, the first call to Write will trigger an implicit WriteHeader(http.StatusOK). Thus explicit calls to WriteHeader are mainly used to send error codes.

type Server

type Server interface {
	Wait(...func())
	Close(context.Context) error
	TLSManager() *autocert.Manager
}

Server defines a type which closes a underline server and returns any error associated with the call.

func Listen

func Listen(tlsOK bool, addr string, handler http.Handler) (Server, error)

Listen will start a server and returns a ServerCloser which will allow closing of the server.

func ListenWith

func ListenWith(tlsconfig *tls.Config, addr string, handler http.Handler) (Server, error)

ListenWith will start a server and returns a ServerCloser which will allow closing of the server.

type TreeMuxHandler

type TreeMuxHandler func(http.ResponseWriter, *http.Request, map[string]string)

TreeMuxHandler defines a function type for the httptreemux.Handler type.

type TreemuxHandlerMW

type TreemuxHandlerMW func(Handler, ...Middleware) httptreemux.HandlerFunc

TreemuxHandlerMW defines a function which wraps a provided http.handlerFunc which encapsulates the original for a underline operation.

func HTTPTreemux

func HTTPTreemux(errHandler ErrorHandler, ops ...Options) TreemuxHandlerMW

HTTPTreemux returns a middleware for usage with the httptreemux router. It ensures to wrap all params into the Context and add necessary paramters as provided for err handling.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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