Documentation ¶
Overview ¶
Package handler provides the types used to coordinate the processing of a web service request.
The core type in this package is WsHandler. A handler (an instance of WsHandler) must be created for every logical web service endpoint in your application. The behaviour and configuration of handlers is described in detail at https://granitic.io/ref/web-service-handlers but a brief description follows.
Declaring handlers ¶
A handler is declared in your component definition file like:
{ "artistHandler": { "type": "handler.WsHandler", "HTTPMethod": "GET", "Logic": "ref:artistLogic", "PathPattern": "^/artist/([\\d]+)[/]?$" }, "artistLogic": { "type": "inventory.ArtistLogic" } }
Each handler must have the following before it is considered a valid web service endpoint.
1. A regular expression that will be matched against the path component of incoming HTTP requests.
2. A single HTTP method that it will be responsible for handling. This is generally GET, POST, PUT or DELETE but any standard or custom HTTP method can be used.
3. A 'logic' component that implements at least WsRequestProcessor (additional WsXXX interfaces can be implemented to support advanced behaviour) OR has a method with the signature ProcessPayload(ctx context.Context, request *ws.Request, response *ws.Response, payload *YourStruct)
Index ¶
- type ErrorTemplate
- type Templated
- type WsHandler
- func (wh *WsHandler) AutoWireable() bool
- func (wh *WsHandler) ComponentName() string
- func (wh *WsHandler) ProvideErrorFinder(finder ws.ServiceErrorFinder)
- func (wh *WsHandler) RegexPattern() string
- func (wh *WsHandler) ServeHTTP(ctx context.Context, w *httpendpoint.HTTPResponseWriter, req *http.Request) context.Context
- func (wh *WsHandler) SetComponentName(name string)
- func (wh *WsHandler) StartComponent() error
- func (wh *WsHandler) SupportedHTTPMethods() []string
- func (wh *WsHandler) SupportsVersion(version httpendpoint.RequiredVersion) bool
- func (wh *WsHandler) VersionAware() bool
- type WsPostProcessor
- type WsPreValidateManipulator
- type WsRequestProcessor
- type WsRequestValidator
- type WsUnmarshallTarget
- type WsVersionAssessor
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type ErrorTemplate ¶
type ErrorTemplate interface { //ErrorTemplateName returns the unique name of a template to use to render response output. ErrorTemplateName() string }
ErrorTemplate is implemented by logic components that need to instruct the web services renderer to use a specific template to render when errors are detected in the response.
type Templated ¶
type Templated interface { // TemplateName returns the unique name of a template to use to render response output. TemplateName() string // UseWhenError returns true if the template returned by TemplateName should be used errors are present in the response. UseWhenError() bool }
Templated is implemented by logic components that need to instruct the web services renderer to use a specific template to render a response.
type WsHandler ¶
type WsHandler struct { // A component able to examine a request and see if the caller is allowed to access this endpoint. AccessChecker ws.AccessChecker // Whether or not the underlying HTTP request and response writer should be made available to request Logic. AllowDirectHTTPAccess bool // Whether or not query parameters should be automatically injected into the request body. AutoBindQuery bool // A component able to use a set of user-defined rules to validate a request. AutoValidator *validate.RuleValidator // A list of field names on the target object into which path parameters (groups in the request regex) should be bound to. BindPathParams []string // Check caller's permissions after request has been parsed (true) or before parsing (false). CheckAccessAfterParse bool // If true, do not automatically return an error response if errors are found during the parsing and binding phases of request processing. DeferFrameworkErrors bool // If true, do not automatically return an error response if errors are found during auto validation. DeferAutoErrors bool // If true, discard the request's query parameters. DisableQueryParsing bool // If true, discard any path parameters found by match the request URI against the PathMatchPattern regex. DisablePathParsing bool // An object that provides access to application defined error messages for use during validation. ErrorFinder ws.ServiceErrorFinder // A map of fields on the request body object and the names of query parameters that should be used to populate them FieldQueryParam map[string]string // An object that provides access to built-in error messages to use when an error is found during the automated phases of request processing. FrameworkErrors *ws.FrameworkErrorGenerator // The HTTP method (GET, POST etc) that this handler supports. HTTPMethod string // A logger injected by the Granitic framework. Note this will be an application logger rather than a framework logger // as instances of WsHandler are considered application components. Log logging.Logger // The object representing the 'logic' behind this handler. Logic interface{} // A component injected by the Granitic framework that can map text representations of query and path parameters to Go // and Granitic types. ParamBinder *ws.ParamBinder // A regex that will be matched against inbound request paths to check if this handler should be used to service the request. PathPattern string // A component that might want to modify a response after it has been processed by the supplied Logic component. PostProcessor WsPostProcessor // A compponent that might want to modify a request after it has been parsed, but before it has been validated. PreValidateManipulator WsPreValidateManipulator // Stop the framework automatically adding this handler to an HTTP server. PreventAutoWiring bool // A component injected by the Granitic framework that writes the response from this handler to an HTTP response. ResponseWriter ws.ResponseWriter // Whether on not the caller needs to be authenticated (using a ws.Identifier) in order to access the logic behind this handler. RequireAuthentication bool // A component injected by the Granitic framework that can extract the body of the incoming HTTP request into a Go struct. Unmarshaller ws.Unmarshaller // A component that can examine a request to determine the calling user/service's identity. UserIdentifier ws.Identifier // A component that can check if this handler supports the version of functionality required by the caller. VersionAssessor WsVersionAssessor // contains filtered or unexported fields }
WsHandler co-ordinates the processing of a web service request for a particular endpoint. Implements ws.Provider
func (*WsHandler) AutoWireable ¶
AutoWireable returns true if this handler should be automatically registered with any instances of httpserver.HTTPServer that are running in the application.
func (*WsHandler) ComponentName ¶
ComponentName implements ComponentNamer.ComponentName
func (*WsHandler) ProvideErrorFinder ¶
func (wh *WsHandler) ProvideErrorFinder(finder ws.ServiceErrorFinder)
ProvideErrorFinder receives a component that can be used to map error codes to categorised errors.
func (*WsHandler) RegexPattern ¶
RegexPattern returns the unparsed regex pattern that should be applicaed to the path of incoming requests to see if this handler should handle the request.
func (*WsHandler) ServeHTTP ¶
func (wh *WsHandler) ServeHTTP(ctx context.Context, w *httpendpoint.HTTPResponseWriter, req *http.Request) context.Context
ServeHTTP is the entry point called by the HTTP server once it has been determined that this handler instance is the correct one to handle the incoming request.
func (*WsHandler) SetComponentName ¶
SetComponentName implements ComponentNamer.SetComponentName
func (*WsHandler) StartComponent ¶
StartComponent is called by the IoC container. Verifies that the minimum set of fields and components and fields have been set (see top of this GoDoc page) and that the configuration of the handler is valid and consistent.
func (*WsHandler) SupportedHTTPMethods ¶
SupportedHTTPMethods returns the HTTP method that this handler supports. Returns an array in order to implement Provider, but will always be a single element array.
func (*WsHandler) SupportsVersion ¶
func (wh *WsHandler) SupportsVersion(version httpendpoint.RequiredVersion) bool
SupportsVersion returns true if this handler supports the version of functionality requested by the caller. Defers to the component injected into this handler's VersionAssessor field.
func (*WsHandler) VersionAware ¶
VersionAware returns true if this handler can be considered when a user requests a specific version of functionality.
type WsPostProcessor ¶
type WsPostProcessor interface { //PostProcess may modify the supplied response object if required. PostProcess(ctx context.Context, handlerName string, request *ws.Request, response *ws.Response) }
WsPostProcessor is implemented to indicate that an object is interested in observing/modifying a web service request after processing has been completed, but before the HTTP response is written. Typical uses are the writing of response headers that are generic to all/most handlers or the recording of metrics.
It is expected that WsPostProcessors may be shared between multiple instances of WsHandler
type WsPreValidateManipulator ¶
type WsPreValidateManipulator interface { // PreValidate returns true if the supplied request is in a suitable state for processing to continue. PreValidate(ctx context.Context, request *ws.Request, errors *ws.ServiceErrors) (proceed bool) }
WsPreValidateManipulator is implemented to indicate that an object is interested in observing/modifying a web service request after it has been unmarshalled and parsed, but before automatic and application-defined validation takes place.
type WsRequestProcessor ¶
type WsRequestProcessor interface { // Process performs the actual 'work' of a web service request. The response parameter will be modified according to // the output or errors that the web service caller should see. Process(ctx context.Context, request *ws.Request, response *ws.Response) }
WsRequestProcessor specifies the minimum required of a component to be considered a 'logic' component suitable for use by a WsHandler.
type WsRequestValidator ¶
type WsRequestValidator interface { // Validate will add one or more CategorisedServiceError objects to the supplied errors parameter if the request is not suitable for further processing. Validate(ctx context.Context, errors *ws.ServiceErrors, request *ws.Request) }
WsRequestValidator is optionally implemented by the same object that is used as a handler's WsRequestProcessor. If implemented, the Validate method will be called to determine whether or not a request should proceed to processing.
type WsUnmarshallTarget ¶
type WsUnmarshallTarget interface {
// UnmarshallTarget returns a pointer to a struct. That struct can be used by the called to parse or map request data (body, query parameters etc) into.
UnmarshallTarget() interface{}
}
WsUnmarshallTarget is implemented by logic components that are able to create target objects for data from a web service request to be parsed into. For example, a web service that supports POST requests will need an object into which the request body can be stored.
type WsVersionAssessor ¶
type WsVersionAssessor interface { // SupportsVersion returns true if the named handle is able to support the requested version. SupportsVersion(handlerName string, version httpendpoint.RequiredVersion) bool }
WsVersionAssessor allows a component to tell Granitic that the object can determine whether or not handler supports a given version of a request.