Documentation
¶
Overview ¶
Package handler provides standard HTTP handlers for the WebPA servers.
Index ¶
- Constants
- func Recover(ctx context.Context, response http.ResponseWriter)
- func WriteError(response http.ResponseWriter, err interface{}) error
- func WriteJsonError(response http.ResponseWriter, code int, message string) error
- type AuthorizationHandler
- type Chain
- type ChainHandler
- func Convey() ChainHandler
- func ConveyCustom(conveyHeader string, encoding *base64.Encoding) ChainHandler
- func DeviceId() ChainHandler
- func DeviceIdCustom(deviceNameHeader string) ChainHandler
- func Listen(listeners ...RequestListener) ChainHandler
- func RequestGate(connection Connection, unavailableStatus int, unavailableMessage string) ChainHandler
- type ChainHandlerFunc
- type Connection
- type ConnectionFunc
- type ContextHandler
- type ContextHandlerFunc
- type HttpError
- type RequestListener
Examples ¶
Constants ¶
const ( // The Content-Type value for JSON JsonContentType string = "application/json; charset=UTF-8" // The Content-Type header ContentTypeHeader string = "Content-Type" // The X-Content-Type-Options header ContentTypeOptionsHeader string = "X-Content-Type-Options" // The X-Webpa-Convey header ConveyHeader string = "X-Webpa-Convey" // DeviceNameHeader is the standard name of the header which carries the WebPA device DeviceNameHeader string = "X-Webpa-Device-Name" // MissingDeviceNameHeaderMessage is the error message indicating that the DeviceNameHeader // was missing from the request. MissingDeviceNameHeaderMessage string = "Missing " + DeviceNameHeader + " header" // InvalidDeviceNameHeaderPattern is the format pattern used to create an error message indicating // that a device name was improperly formatted. InvalidDeviceNameHeaderPattern string = "Invalid " + DeviceNameHeader + " header [%s]: %s" // InvalidConveyPattern is the format pattern used to create an error message indicating that // a convey payload was invalid. InvalidConveyPattern string = "Invalid " + ConveyHeader + " header [%s]: %v" // NoSniff is the value used for content options for errors written by this package NoSniff string = "nosniff" )
Variables ¶
This section is empty.
Functions ¶
func Recover ¶
func Recover(ctx context.Context, response http.ResponseWriter)
Recover provides panic recovery for a chain of requests. This function *must* be called as a deferred function.
func WriteError ¶
func WriteError(response http.ResponseWriter, err interface{}) error
WriteError handles writing errors, possibly from panic, in a standard way. This method permits a variety of types for the err value.
func WriteJsonError ¶
func WriteJsonError(response http.ResponseWriter, code int, message string) error
WriteJsonError writes a standard JSON error to the response
Types ¶
type AuthorizationHandler ¶
type AuthorizationHandler struct {
HeaderName string
ForbiddenStatusCode int
Validator secure.Validator
Logger logging.Logger
}
AuthorizationHandler provides decoration for http.Handler instances and will ensure that requests pass the validator. Note that secure.Validators is a Validator implementation that allows chaining validators together via logical OR.
type Chain ¶
type Chain []ChainHandler
Chain represents an ordered slice of ChainHandlers that will be applied to each request.
Example ¶
logger := &logging.LoggerWriter{os.Stdout}
ctx := fact.SetLogger(context.Background(), logger)
contextHandler := ContextHandlerFunc(func(ctx context.Context, response http.ResponseWriter, request *http.Request) {
logger := fact.MustLogger(ctx)
payloadJson, err := json.Marshal(fact.MustConvey(ctx))
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to marshal convey payload: %v\n", err)
return
}
logger.Info("%s", payloadJson)
logger.Info("%s", fact.MustDeviceId(ctx))
})
response, request := dummyHttpOperation()
request.Header.Add(ConveyHeader, "eyJuYW1lIjoidmFsdWUifQ==")
request.Header.Add(DeviceNameHeader, "mac:111122223333")
Chain{
Convey(),
DeviceId(),
}.Decorate(ctx, contextHandler).ServeHTTP(response, request)
Output: [INFO] {"name":"value"} [INFO] mac:111122223333
type ChainHandler ¶
type ChainHandler interface {
ServeHTTP(context.Context, http.ResponseWriter, *http.Request, ContextHandler)
}
ChainHandler represents an HTTP handler type that is one part of a chain of handlers.
func Convey ¶
func Convey() ChainHandler
Example ¶
contextHandler := ContextHandlerFunc(func(ctx context.Context, response http.ResponseWriter, request *http.Request) {
payload := fact.MustConvey(ctx)
payloadJson, err := json.Marshal(payload)
if err != nil {
fmt.Fprintf(os.Stderr, "Could not marshal payload: %v\n", err)
} else {
fmt.Printf("%s\n", payloadJson)
}
})
response, request := dummyHttpOperation()
request.Header.Add(ConveyHeader, "eyJuYW1lIjoidmFsdWUifQ==")
Convey().ServeHTTP(context.Background(), response, request, contextHandler)
Output: {"name":"value"}
func ConveyCustom ¶
func ConveyCustom(conveyHeader string, encoding *base64.Encoding) ChainHandler
func DeviceId ¶
func DeviceId() ChainHandler
DeviceId parses out the DeviceNameHeader from the request
Example ¶
logger := &logging.LoggerWriter{os.Stdout}
ctx := fact.SetLogger(context.Background(), logger)
contextHandler := ContextHandlerFunc(func(ctx context.Context, response http.ResponseWriter, request *http.Request) {
deviceId := fact.MustDeviceId(ctx)
fact.MustLogger(ctx).Info("%s", deviceId)
})
response, request := dummyHttpOperation()
request.Header.Add(DeviceNameHeader, "mac:111122223333")
DeviceId().ServeHTTP(ctx, response, request, contextHandler)
Output: [INFO] mac:111122223333
func DeviceIdCustom ¶
func DeviceIdCustom(deviceNameHeader string) ChainHandler
DeviceIdCustom allows the header used for the device name to be customized
func Listen ¶
func Listen(listeners ...RequestListener) ChainHandler
Listen produces a ChainHandler that notifies the given list of listeners of request events. This handler also provides panic recovery. Upon a recovered panic, this ChainHandler ensures that listener.RequestCompleted is invoked.
func RequestGate ¶
func RequestGate(connection Connection, unavailableStatus int, unavailableMessage string) ChainHandler
RequestGate returns a ChainHandler whose requests are gated by the given RequestGate
type ChainHandlerFunc ¶
type ChainHandlerFunc func(context.Context, http.ResponseWriter, *http.Request, ContextHandler)
ChainHandlerFunc is a function type that implements ChainHandler
func (ChainHandlerFunc) ServeHTTP ¶
func (f ChainHandlerFunc) ServeHTTP(requestContext context.Context, response http.ResponseWriter, request *http.Request, next ContextHandler)
type Connection ¶
type Connection interface {
// Connected returns a boolean indicating whether the abstract system
// denoted by this instance is available.
Connected() bool
}
Connection represents some sort of subsystem or remote system that has a notion of being available
func MergeConnections ¶
func MergeConnections(connections ...Connection) Connection
MergeConnections returns an aggregate Connection object that returns false if any of the given Connection objects return false.
type ConnectionFunc ¶
type ConnectionFunc func() bool
ConnectionFunc is a function type that implements Connection
func (ConnectionFunc) Connected ¶
func (f ConnectionFunc) Connected() bool
type ContextHandler ¶
type ContextHandler interface {
// ServeHTTP handles an HTTP request within an enclosing WebPA context
ServeHTTP(context.Context, http.ResponseWriter, *http.Request)
}
ContextHandler defines the behavior of types which can handle HTTP requests inside a WebPA context
func Hash ¶
func Hash(serviceHash hash.ServiceHash) ContextHandler
Hash returns a redirector using the default status code of http.StatusTemporaryRedirect.
Example ¶
var output bytes.Buffer
logger := &logging.LoggerWriter{&output}
ctx := fact.SetLogger(context.Background(), logger)
deviceID, err := device.ParseID("mac:111122223333")
if err != nil {
fmt.Fprintf(os.Stderr, "Error while parsing device id: %v\n", err)
return
}
ctx = fact.SetDeviceId(ctx, deviceID)
serviceHash := &testServiceHash{value: "http://comcast.net"}
response, request := dummyHttpOperation()
request.URL.Path = "/foo/bar"
hash := Hash(serviceHash)
hash.ServeHTTP(ctx, response, request)
fmt.Println(response.Code)
fmt.Println(response.Header().Get("Location"))
Output: 307 http://comcast.net/foo/bar
func HashCustom ¶
func HashCustom(serviceHash hash.ServiceHash, redirectCode int) ContextHandler
HashCustom provides a ContextHandler that redirects requests based on a ServiceHash. The context must have a device identifier, which is then used as the key supplied to the hash.
type ContextHandlerFunc ¶
ContextHandlerFunc is a function type that implements ContextHandler
func (ContextHandlerFunc) ServeHTTP ¶
func (f ContextHandlerFunc) ServeHTTP(ctx context.Context, response http.ResponseWriter, request *http.Request)
type HttpError ¶
HttpError extends the error interface to include error information for HTTP responses
func NewHttpError ¶
NewHttpError creates a new HttpError object. This object implements go's builtin error interface.
type RequestListener ¶
type RequestListener interface {
// RequestReceived is invoked anytime a handler receives a request
RequestReceived(*http.Request)
// RequestCompleted is invoked after the response has been written.
// The first parameter is the response status code, e.g. http.StatusOk
RequestCompleted(int, *http.Request)
}
RequestListener gets notified of certain high-level request events
func NewHealthRequestListener ¶
func NewHealthRequestListener(sink healthEventSink) RequestListener
NewHealthRequestListener returns a new RequestListener which dispatches request stats