const ( MIME_XML = "application/xml" // Accept or Content-Type used in Consumes() and/or Produces() MIME_JSON = "application/json" // Accept or Content-Type used in Consumes() and/or Produces() MIME_ZIP = "application/zip" // Accept or Content-Type used in Consumes() and/or Produces() MIME_OCTET = "application/octet-stream" // If Content-Type is not present in request, use the default HEADER_Allow = "Allow" HEADER_Accept = "Accept" HEADER_Origin = "Origin" HEADER_ContentType = "Content-Type" HEADER_ContentDisposition = "Content-Disposition" HEADER_LastModified = "Last-Modified" HEADER_AcceptEncoding = "Accept-Encoding" HEADER_ContentEncoding = "Content-Encoding" HEADER_AccessControlExposeHeaders = "Access-Control-Expose-Headers" HEADER_AccessControlRequestMethod = "Access-Control-Request-Method" HEADER_AccessControlRequestHeaders = "Access-Control-Request-Headers" HEADER_AccessControlAllowMethods = "Access-Control-Allow-Methods" HEADER_AccessControlAllowOrigin = "Access-Control-Allow-Origin" HEADER_AccessControlAllowCredentials = "Access-Control-Allow-Credentials" HEADER_AccessControlAllowHeaders = "Access-Control-Allow-Headers" HEADER_AccessControlMaxAge = "Access-Control-Max-Age" ENCODING_GZIP = "gzip" ENCODING_DEFLATE = "deflate" )
const ( // PathParameterKind = indicator of Request parameter type "path" PathParameterKind = iota // QueryParameterKind = indicator of Request parameter type "query" QueryParameterKind // BodyParameterKind = indicator of Request parameter type "body" BodyParameterKind // HeaderParameterKind = indicator of Request parameter type "header" HeaderParameterKind // FormParameterKind = indicator of Request parameter type "form" FormParameterKind // MultiPartFormParameterKind = indicator of Request parameter type "multipart/form-data" MultiPartFormParameterKind // CollectionFormatCSV comma separated values `foo,bar` CollectionFormatCSV = CollectionFormat("csv") // CollectionFormatSSV space separated values `foo bar` CollectionFormatSSV = CollectionFormat("ssv") // CollectionFormatTSV tab separated values `foo\tbar` CollectionFormatTSV = CollectionFormat("tsv") // CollectionFormatPipes pipe separated values `foo|bar` CollectionFormatPipes = CollectionFormat("pipes") // CollectionFormatMulti corresponds to multiple parameter instances instead of multiple values for a single // instance `foo=bar&foo=baz`. This is valid only for QueryParameters and FormParameters CollectionFormatMulti = CollectionFormat("multi") )
var ( MarshalIndent = json.MarshalIndent NewDecoder = json.NewDecoder NewEncoder = json.NewEncoder )
DefaultResponseMimeType is DEPRECATED, use DefaultResponseContentType(mime)
var DefaultResponseMimeType string
If set the true then panics will not be caught to return HTTP 500. In that case, Route functions are responsible for handling any error situation. Default value is false = recover from panics. This has performance implications. OBSOLETE ; use restful.DefaultContainer.DoNotRecover(true)
var DoNotRecover = false
OBSOLETE : use restful.DefaultContainer.EnableContentEncoding(true) to change this setting.
var EnableContentEncoding = false
PrettyPrintResponses controls the indentation feature of XML and JSON serialization
var PrettyPrintResponses = true
TrimRightSlashEnabled controls whether - path on route building is using path.Join - the path of the incoming request is trimmed of its slash suffux. Value of true matches the behavior of <= 3.9.0
var TrimRightSlashEnabled = true
func Add(service *WebService)
Add registers a new WebService add it to the DefaultContainer.
func DefaultRequestContentType(mime string)
If ContentType is missing or */* is given then fall back to this type, otherwise a "Unable to unmarshal content of type:" response is returned. Valid values are restful.MIME_JSON and restful.MIME_XML Example:
restful.DefaultRequestContentType(restful.MIME_JSON)
func DefaultResponseContentType(mime string)
DefaultResponseContentType set a default. If Accept header matching fails, fall back to this type. Valid values are restful.MIME_JSON and restful.MIME_XML Example:
restful.DefaultResponseContentType(restful.MIME_JSON)
func EnableTracing(enabled bool)
EnableTracing can be used to Trace logging on and off.
func Filter(filter FilterFunction)
Filter appends a container FilterFunction from the DefaultContainer. These are called before dispatching a http.Request to a WebService.
func NoBrowserCacheFilter(req *Request, resp *Response, chain *FilterChain)
NoBrowserCacheFilter is a filter function to set HTTP headers that disable browser caching See examples/restful-no-cache-filter.go for usage
func RegisterEntityAccessor(mime string, erw EntityReaderWriter)
RegisterEntityAccessor add/overrides the ReaderWriter for encoding content with this MIME type.
func SetCompressorProvider(p CompressorProvider)
SetCompressorProvider sets the actual provider of compressors (zlib or gzip).
func SetLogger(customLogger log.StdLogger)
SetLogger exposes the setter for the global logger on the top-level package
func TraceLogger(logger log.StdLogger)
TraceLogger enables detailed logging of Http request matching and filter invocation. Default no logger is set. You may call EnableTracing() directly to enable trace logging to the package-wide logger.
BoundedCachedCompressors is a CompressorProvider that uses a cache with a fixed amount of writers and readers (resources). If a new resource is acquired and all are in use, it will return a new unmanaged resource.
type BoundedCachedCompressors struct {
// contains filtered or unexported fields
}
▹ Example
func NewBoundedCachedCompressors(writersCapacity, readersCapacity int) *BoundedCachedCompressors
NewBoundedCachedCompressors returns a new, with filled cache, BoundedCachedCompressors.
func (b *BoundedCachedCompressors) AcquireGzipReader() *gzip.Reader
AcquireGzipReader returns a *gzip.Reader. Needs to be released.
func (b *BoundedCachedCompressors) AcquireGzipWriter() *gzip.Writer
AcquireGzipWriter returns an resettable *gzip.Writer. Needs to be released.
func (b *BoundedCachedCompressors) AcquireZlibWriter() *zlib.Writer
AcquireZlibWriter returns an resettable *zlib.Writer. Needs to be released.
func (b *BoundedCachedCompressors) ReleaseGzipReader(r *gzip.Reader)
ReleaseGzipReader accepts a reader (does not have to be one that was cached) only when the cache has room for it. It will ignore it otherwise.
func (b *BoundedCachedCompressors) ReleaseGzipWriter(w *gzip.Writer)
ReleaseGzipWriter accepts a writer (does not have to be one that was cached) only when the cache has room for it. It will ignore it otherwise.
func (b *BoundedCachedCompressors) ReleaseZlibWriter(w *zlib.Writer)
ReleaseZlibWriter accepts a writer (does not have to be one that was cached) only when the cache has room for it. It will ignore it otherwise.
type CollectionFormat string
func (cf CollectionFormat) String() string
CompressingResponseWriter is a http.ResponseWriter that can perform content encoding (gzip and zlib)
type CompressingResponseWriter struct {
// contains filtered or unexported fields
}
func NewCompressingResponseWriter(httpWriter http.ResponseWriter, encoding string) (*CompressingResponseWriter, error)
NewCompressingResponseWriter create a CompressingResponseWriter for a known encoding = {gzip,deflate}
func (c *CompressingResponseWriter) Close() error
Close the underlying compressor
func (c *CompressingResponseWriter) CloseNotify() <-chan bool
CloseNotify is part of http.CloseNotifier interface
func (c *CompressingResponseWriter) Flush()
Flush is part of http.Flusher interface. Noop if the underlying writer doesn't support it.
func (c *CompressingResponseWriter) Header() http.Header
Header is part of http.ResponseWriter interface
func (c *CompressingResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
Hijack implements the Hijacker interface This is especially useful when combining Container.EnabledContentEncoding in combination with websockets (for instance gorilla/websocket)
func (c *CompressingResponseWriter) Write(bytes []byte) (int, error)
Write is part of http.ResponseWriter interface It is passed through the compressor
func (c *CompressingResponseWriter) WriteHeader(status int)
WriteHeader is part of http.ResponseWriter interface
CompressorProvider describes a component that can provider compressors for the std methods.
type CompressorProvider interface { // Returns a *gzip.Writer which needs to be released later. // Before using it, call Reset(). AcquireGzipWriter() *gzip.Writer // Releases an acquired *gzip.Writer. ReleaseGzipWriter(w *gzip.Writer) // Returns a *gzip.Reader which needs to be released later. AcquireGzipReader() *gzip.Reader // Releases an acquired *gzip.Reader. ReleaseGzipReader(w *gzip.Reader) // Returns a *zlib.Writer which needs to be released later. // Before using it, call Reset(). AcquireZlibWriter() *zlib.Writer // Releases an acquired *zlib.Writer. ReleaseZlibWriter(w *zlib.Writer) }
func CurrentCompressorProvider() CompressorProvider
CurrentCompressorProvider returns the current CompressorProvider. It is initialized using a SyncPoolCompessors.
Container holds a collection of WebServices and a http.ServeMux to dispatch http requests. The requests are further dispatched to routes of WebServices using a RouteSelector
type Container struct { ServeMux *http.ServeMux // contains filtered or unexported fields }
DefaultContainer is a restful.Container that uses http.DefaultServeMux
var DefaultContainer *Container
▹ Example
func NewContainer() *Container
NewContainer creates a new Container using a new ServeMux and default router (CurlyRouter)
func (c *Container) Add(service *WebService) *Container
Add a WebService to the Container. It will detect duplicate root paths and exit in that case.
func (c *Container) Dispatch(httpWriter http.ResponseWriter, httpRequest *http.Request)
Dispatch the incoming Http Request to a matching WebService.
func (c *Container) DoNotRecover(doNot bool)
DoNotRecover controls whether panics will be caught to return HTTP 500. If set to true, Route functions are responsible for handling any error situation. Default value is true.
func (c *Container) EnableContentEncoding(enabled bool)
EnableContentEncoding (default=false) allows for GZIP or DEFLATE encoding of responses.
func (c *Container) Filter(filter FilterFunction)
Filter appends a container FilterFunction. These are called before dispatching a http.Request to a WebService from the container
func (c *Container) Handle(pattern string, handler http.Handler)
Handle registers the handler for the given pattern. If a handler already exists for pattern, Handle panics.
func (c *Container) HandleWithFilter(pattern string, handler http.Handler)
HandleWithFilter registers the handler for the given pattern. Container's filter chain is applied for handler. If a handler already exists for pattern, HandleWithFilter panics.
func (c *Container) OPTIONSFilter(req *Request, resp *Response, chain *FilterChain)
OPTIONSFilter is a filter function that inspects the Http Request for the OPTIONS method and provides the response with a set of allowed methods for the request URL Path. As for any filter, you can also install it for a particular WebService within a Container. Note: this filter is not needed when using CrossOriginResourceSharing (for CORS).
▹ Example
func (c *Container) RecoverHandler(handler RecoverHandleFunction)
RecoverHandler changes the default function (logStackOnRecover) to be called when a panic is detected. DoNotRecover must be have its default value (=false).
func (c *Container) RegisteredWebServices() []*WebService
RegisteredWebServices returns the collections of added WebServices
func (c *Container) Remove(ws *WebService) error
func (c *Container) Router(aRouter RouteSelector)
Router changes the default Router (currently CurlyRouter)
func (c *Container) ServeHTTP(httpWriter http.ResponseWriter, httpRequest *http.Request)
ServeHTTP implements net/http.Handler therefore a Container can be a Handler in a http.Server
func (c *Container) ServiceErrorHandler(handler ServiceErrorHandleFunction)
ServiceErrorHandler changes the default function (writeServiceError) to be called when a ServiceError is detected.
CrossOriginResourceSharing is used to create a Container Filter that implements CORS. Cross-origin resource sharing (CORS) is a mechanism that allows JavaScript on a web page to make XMLHttpRequests to another domain, not the domain the JavaScript originated from.
http://en.wikipedia.org/wiki/Cross-origin_resource_sharing http://enable-cors.org/server.html http://www.html5rocks.com/en/tutorials/cors/#toc-handling-a-not-so-simple-request
type CrossOriginResourceSharing struct { ExposeHeaders []string // list of Header names // AllowedHeaders is alist of Header names. Checking is case-insensitive. // The list may contain the special wildcard string ".*" ; all is allowed AllowedHeaders []string // AllowedDomains is a list of allowed values for Http Origin. // The list may contain the special wildcard string ".*" ; all is allowed // If empty all are allowed. AllowedDomains []string // AllowedDomainFunc is optional and is a function that will do the check // when the origin is not part of the AllowedDomains and it does not contain the wildcard ".*". AllowedDomainFunc func(origin string) bool // AllowedMethods is either empty or has a list of http methods names. Checking is case-insensitive. AllowedMethods []string MaxAge int // number of seconds before requiring new Options request CookiesAllowed bool Container *Container // contains filtered or unexported fields }
▹ Example
func (c CrossOriginResourceSharing) Filter(req *Request, resp *Response, chain *FilterChain)
Filter is a filter function that implements the CORS flow as documented on http://enable-cors.org/server.html and http://www.html5rocks.com/static/images/cors_server_flowchart.png
CurlyRouter expects Routes with paths that contain zero or more parameters in curly brackets.
type CurlyRouter struct{}
func (c CurlyRouter) SelectRoute( webServices []*WebService, httpRequest *http.Request) (selectedService *WebService, selected *Route, err error)
SelectRoute is part of the Router interface and returns the best match for the WebService and its Route for the given Request.
EntityReaderWriter can read and write values using an encoding such as JSON,XML.
type EntityReaderWriter interface { // Read a serialized version of the value from the request. // The Request may have a decompressing reader. Depends on Content-Encoding. Read(req *Request, v interface{}) error // Write a serialized version of the value on the response. // The Response may have a compressing writer. Depends on Accept-Encoding. // status should be a valid Http Status code Write(resp *Response, status int, v interface{}) error }
func NewEntityAccessorJSON(contentType string) EntityReaderWriter
NewEntityAccessorJSON returns a new EntityReaderWriter for accessing JSON content. This package is already initialized with such an accessor using the MIME_JSON contentType.
func NewEntityAccessorXML(contentType string) EntityReaderWriter
NewEntityAccessorXML returns a new EntityReaderWriter for accessing XML content. This package is already initialized with such an accessor using the MIME_XML contentType.
ExtensionProperties provides storage of vendor extensions for entities
type ExtensionProperties struct { // Extensions vendor extensions used to describe extra functionality // (https://swagger.io/docs/specification/2-0/swagger-extensions/) Extensions map[string]interface{} }
func (ep *ExtensionProperties) AddExtension(key string, value interface{})
AddExtension adds or updates a key=value pair to the extension map.
FilterChain is a request scoped object to process one or more filters before calling the target RouteFunction.
type FilterChain struct { Filters []FilterFunction // ordered list of FilterFunction Index int // index into filters that is currently in progress Target RouteFunction // function to call after passing all filters ParameterDocs []*Parameter // the parameter docs for the route Operation string // the name of the operation }
func (f *FilterChain) ProcessFilter(request *Request, response *Response)
ProcessFilter passes the request,response pair through the next of Filters. Each filter can decide to proceed to the next Filter or handle the Response itself.
FilterFunction definitions must call ProcessFilter on the FilterChain to pass on the control and eventually call the RouteFunction
type FilterFunction func(*Request, *Response, *FilterChain)
func HttpMiddlewareHandlerToFilter(middleware HttpMiddlewareHandler) FilterFunction
HttpMiddlewareHandlerToFilter converts a HttpMiddlewareHandler to a FilterFunction.
func OPTIONSFilter() FilterFunction
OPTIONSFilter is a filter function that inspects the Http Request for the OPTIONS method and provides the response with a set of allowed methods for the request URL Path. Note: this filter is not needed when using CrossOriginResourceSharing (for CORS).
▹ Example
Header describes a header for a response of the API
For more information: http://goo.gl/8us55a#headerObject
type Header struct { *Items Description string }
HttpMiddlewareHandler is a function that takes a http.Handler and returns a http.Handler
type HttpMiddlewareHandler func(http.Handler) http.Handler
Items describe swagger simple schemas for headers
type Items struct { Type string Format string Items *Items CollectionFormat string Default interface{} }
Parameter is for documententing the parameter used in a Http Request ParameterData kinds are Path,Query and Body
type Parameter struct {
// contains filtered or unexported fields
}
func BodyParameter(name, description string) *Parameter
BodyParameter creates a new Parameter of kind Body for documentation purposes. It is initialized as required without a DataType.
func FormParameter(name, description string) *Parameter
FormParameter creates a new Parameter of kind Form (using application/x-www-form-urlencoded) for documentation purposes. It is initialized as required with string as its DataType.
func HeaderParameter(name, description string) *Parameter
HeaderParameter creates a new Parameter of kind (Http) Header for documentation purposes. It is initialized as not required with string as its DataType.
func MultiPartFormParameter(name, description string) *Parameter
func PathParameter(name, description string) *Parameter
PathParameter creates a new Parameter of kind Path for documentation purposes. It is initialized as required with string as its DataType.
func QueryParameter(name, description string) *Parameter
QueryParameter creates a new Parameter of kind Query for documentation purposes. It is initialized as not required with string as its DataType.
func (p *Parameter) AddExtension(key string, value interface{}) *Parameter
AddExtension adds or updates a key=value pair to the extension map
func (p *Parameter) AllowEmptyValue(multiple bool) *Parameter
AllowEmptyValue sets the AllowEmptyValue field and returns the receiver
func (p *Parameter) AllowMultiple(multiple bool) *Parameter
AllowMultiple sets the allowMultiple field and returns the receiver
func (p *Parameter) AllowableValues(values map[string]string) *Parameter
AllowableValues is deprecated. Use PossibleValues instead. Both will be set.
func (p *Parameter) CollectionFormat(format CollectionFormat) *Parameter
CollectionFormat sets the collection format for an array type
func (p *Parameter) Data() ParameterData
Data returns the state of the Parameter
func (p *Parameter) DataFormat(formatName string) *Parameter
DataFormat sets the dataFormat field for Swagger UI
func (p *Parameter) DataType(typeName string) *Parameter
DataType sets the dataType field and returns the receiver
func (p *Parameter) DefaultValue(stringRepresentation string) *Parameter
DefaultValue sets the default value field and returns the receiver
func (p *Parameter) Description(doc string) *Parameter
Description sets the description value field and returns the receiver
func (p *Parameter) Kind() int
Kind returns the parameter type indicator (see const for valid values)
func (p *Parameter) MaxItems(maxItems int64) *Parameter
MaxItems sets the maxItems field and returns the receiver
func (p *Parameter) MaxLength(maxLength int64) *Parameter
MaxLength sets the maxLength field and returns the receiver
func (p *Parameter) Maximum(maximum float64) *Parameter
Maximum sets the maximum field and returns the receiver
func (p *Parameter) MinItems(minItems int64) *Parameter
MinItems sets the minItems field and returns the receiver
func (p *Parameter) MinLength(minLength int64) *Parameter
MinLength sets the minLength field and returns the receiver
func (p *Parameter) Minimum(minimum float64) *Parameter
Minimum sets the minimum field and returns the receiver
func (p *Parameter) Pattern(pattern string) *Parameter
Pattern sets the pattern field and returns the receiver
func (p *Parameter) PossibleValues(values []string) *Parameter
PossibleValues sets the possible values field and returns the receiver
func (p *Parameter) Required(required bool) *Parameter
Required sets the required field and returns the receiver
func (p *Parameter) UniqueItems(uniqueItems bool) *Parameter
UniqueItems sets the uniqueItems field and returns the receiver
ParameterData represents the state of a Parameter. It is made public to make it accessible to e.g. the Swagger package.
type ParameterData struct { ExtensionProperties Name, Description, DataType, DataFormat string Kind int Required bool // AllowableValues is deprecated. Use PossibleValues instead AllowableValues map[string]string PossibleValues []string AllowMultiple bool AllowEmptyValue bool DefaultValue string CollectionFormat string Pattern string Minimum *float64 Maximum *float64 MinLength *int64 MaxLength *int64 MinItems *int64 MaxItems *int64 UniqueItems bool }
PathProcessor is extra behaviour that a Router can provide to extract path parameters from the path. If a Router does not implement this interface then the default behaviour will be used.
type PathProcessor interface { // ExtractParameters gets the path parameters defined in the route and webService from the urlPath ExtractParameters(route *Route, webService *WebService, urlPath string) map[string]string }
RecoverHandleFunction declares functions that can be used to handle a panic situation. The first argument is what recover() returns. The second must be used to communicate an error response.
type RecoverHandleFunction func(interface{}, http.ResponseWriter)
Request is a wrapper for a http Request that provides convenience methods
type Request struct { Request *http.Request // contains filtered or unexported fields }
func NewRequest(httpRequest *http.Request) *Request
func (r Request) Attribute(name string) interface{}
Attribute returns the value associated to the given name. Returns nil if absent.
func (r *Request) BodyParameter(name string) (string, error)
BodyParameter parses the body of the request (once for typically a POST or a PUT) and returns the value of the given name or an error.
func (r *Request) HeaderParameter(name string) string
HeaderParameter returns the HTTP Header value of a Header name or empty if missing
func (r *Request) PathParameter(name string) string
PathParameter accesses the Path parameter value by its name
func (r *Request) PathParameters() map[string]string
PathParameters accesses the Path parameter values
func (r *Request) QueryParameter(name string) string
QueryParameter returns the (first) Query parameter value by its name
func (r *Request) QueryParameters(name string) []string
QueryParameters returns the all the query parameters values by name
func (r *Request) ReadEntity(entityPointer interface{}) (err error)
ReadEntity checks the Accept header and reads the content into the entityPointer.
func (r Request) SelectedRoute() RouteReader
SelectedRoute returns a reader to access the selected Route by the container Returns nil if no route was matched.
func (r Request) SelectedRoutePath() string
SelectedRoutePath root path + route path that matched the request, e.g. /meetings/{id}/attendees If no route was matched then return an empty string.
func (r *Request) SetAttribute(name string, value interface{})
SetAttribute adds or replaces the attribute with the given value.
Response is a wrapper on the actual http ResponseWriter It provides several convenience methods to prepare and write response content.
type Response struct { http.ResponseWriter // contains filtered or unexported fields }
func NewResponse(httpWriter http.ResponseWriter) *Response
NewResponse creates a new response based on a http ResponseWriter.
func (r Response) AddHeader(header string, value string) Response
AddHeader is a shortcut for .Header().Add(header,value)
func (r Response) CloseNotify() <-chan bool
CloseNotify is part of http.CloseNotifier interface
func (r Response) ContentLength() int
ContentLength returns the number of bytes written for the response content. Note that this value is only correct if all data is written through the Response using its Write* methods. Data written directly using the underlying http.ResponseWriter is not accounted for.
func (r *Response) EntityWriter() (EntityReaderWriter, bool)
EntityWriter returns the registered EntityWriter that the entity (requested resource) can write according to what the request wants (Accept) and what the Route can produce or what the restful defaults say. If called before WriteEntity and WriteHeader then a false return value can be used to write a 406: Not Acceptable.
func (r Response) Error() error
Error returns the err created by WriteError
func (r *Response) Flush()
Flush implements http.Flusher interface, which sends any buffered data to the client.
func (r *Response) Hijack() (net.Conn, *bufio.ReadWriter, error)
Hijack implements the http.Hijacker interface. This expands the Response to fulfill http.Hijacker if the underlying http.ResponseWriter supports it.
func (r Response) InternalServerError() Response
InternalServerError writes the StatusInternalServerError header. DEPRECATED, use WriteErrorString(http.StatusInternalServerError,reason)
func (r *Response) PrettyPrint(bePretty bool)
PrettyPrint changes whether this response must produce pretty (line-by-line, indented) JSON or XML output.
func (r *Response) SetRequestAccepts(mime string)
SetRequestAccepts tells the response what Mime-type(s) the HTTP request said it wants to accept. Exposed for testing.
func (r Response) StatusCode() int
StatusCode returns the code that has been written using WriteHeader.
func (r *Response) Write(bytes []byte) (int, error)
Write writes the data to the connection as part of an HTTP reply. Write is part of http.ResponseWriter interface.
func (r *Response) WriteAsJson(value interface{}) error
WriteAsJson is a convenience method for writing a value in json. It uses the standard encoding/json package for marshalling the value ; not using a registered EntityReaderWriter.
func (r *Response) WriteAsXml(value interface{}) error
WriteAsXml is a convenience method for writing a value in xml (requires Xml tags on the value) It uses the standard encoding/xml package for marshalling the value ; not using a registered EntityReaderWriter.
func (r *Response) WriteEntity(value interface{}) error
WriteEntity calls WriteHeaderAndEntity with Http Status OK (200)
func (r *Response) WriteError(httpStatus int, err error) (writeErr error)
WriteError writes the http status and the error string on the response. err can be nil. Return an error if writing was not successful.
func (r *Response) WriteErrorString(httpStatus int, errorReason string) error
WriteErrorString is a convenience method for an error status with the actual error
func (r *Response) WriteHeader(httpStatus int)
WriteHeader is overridden to remember the Status Code that has been written. Changes to the Header of the response have no effect after this.
func (r *Response) WriteHeaderAndEntity(status int, value interface{}) error
WriteHeaderAndEntity marshals the value using the representation denoted by the Accept Header and the registered EntityWriters. If no Accept header is specified (or */*) then respond with the Content-Type as specified by the first in the Route.Produces. If an Accept header is specified then respond with the Content-Type as specified by the first in the Route.Produces that is matched with the Accept header. If the value is nil then no response is send except for the Http status. You may want to call WriteHeader(http.StatusNotFound) instead. If there is no writer available that can represent the value in the requested MIME type then Http Status NotAcceptable is written. Current implementation ignores any q-parameters in the Accept Header. Returns an error if the value could not be written on the response.
func (r *Response) WriteHeaderAndJson(status int, value interface{}, contentType string) error
WriteHeaderAndJson is a convenience method for writing the status and a value in Json with a given Content-Type. It uses the standard encoding/json package for marshalling the value ; not using a registered EntityReaderWriter.
func (r *Response) WriteHeaderAndXml(status int, value interface{}) error
WriteHeaderAndXml is a convenience method for writing a status and value in xml (requires Xml tags on the value) It uses the standard encoding/xml package for marshalling the value ; not using a registered EntityReaderWriter.
func (r *Response) WriteJson(value interface{}, contentType string) error
WriteJson is a convenience method for writing a value in Json with a given Content-Type. It uses the standard encoding/json package for marshalling the value ; not using a registered EntityReaderWriter.
func (r *Response) WriteServiceError(httpStatus int, err ServiceError) error
WriteServiceError is a convenience method for a responding with a status and a ServiceError
ResponseError represents a response; not necessarily an error.
type ResponseError struct { ExtensionProperties Code int Message string Model interface{} Headers map[string]Header IsDefault bool }
Route binds a HTTP Method,Path,Consumes combination to a RouteFunction.
type Route struct { ExtensionProperties Method string Produces []string Consumes []string Path string // webservice root path + described path Function RouteFunction Filters []FilterFunction If []RouteSelectionConditionFunction // documentation Doc string Notes string Operation string ParameterDocs []*Parameter ResponseErrors map[int]ResponseError DefaultResponse *ResponseError ReadSample, WriteSample interface{} // structs that model an example request or response payload WriteSamples []interface{} // if more than one return types is possible (oneof) then this will contain multiple values // Extra information used to store custom information about the route. Metadata map[string]interface{} // marks a route as deprecated Deprecated bool // contains filtered or unexported fields }
func (r *Route) EnableContentEncoding(enabled bool)
EnableContentEncoding (default=false) allows for GZIP or DEFLATE encoding of responses. Overrides the container.contentEncodingEnabled value.
func (r *Route) String() string
for debugging
RouteBuilder is a helper to construct Routes.
type RouteBuilder struct {
// contains filtered or unexported fields
}
func (b *RouteBuilder) AddExtension(key string, value interface{}) *RouteBuilder
AddExtension adds or updates a key=value pair to the extensions map.
func (b *RouteBuilder) AllowedMethodsWithoutContentType(methods []string) *RouteBuilder
AllowedMethodsWithoutContentType overrides the default list GET,HEAD,OPTIONS,DELETE,TRACE If a request does not include a content-type header then depending on the method, it may return a 415 Unsupported Media. Must have uppercase HTTP Method names such as GET,HEAD,OPTIONS,...
func (b *RouteBuilder) Build() Route
Build creates a new Route using the specification details collected by the RouteBuilder
func (b *RouteBuilder) Consumes(mimeTypes ...string) *RouteBuilder
Consumes specifies what MIME types can be consumes ; the Accept Http header must matched any of these
func (b *RouteBuilder) ContentEncodingEnabled(enabled bool) *RouteBuilder
ContentEncodingEnabled allows you to override the Containers value for auto-compressing this route response.
func (b *RouteBuilder) DefaultReturns(message string, model interface{}) *RouteBuilder
DefaultReturns is a special Returns call that sets the default of the response.
func (b *RouteBuilder) Deprecate() *RouteBuilder
Deprecate sets the value of deprecated to true. Deprecated routes have a special UI treatment to warn against use
func (b *RouteBuilder) Do(oneArgBlocks ...func(*RouteBuilder)) *RouteBuilder
Do evaluates each argument with the RouteBuilder itself. This allows you to follow DRY principles without breaking the fluent programming style. Example:
ws.Route(ws.DELETE("/{name}").To(t.deletePerson).Do(Returns200, Returns500)) func Returns500(b *RouteBuilder) { b.Returns(500, "Internal Server Error", restful.ServiceError{}) }
func (b *RouteBuilder) Doc(documentation string) *RouteBuilder
Doc tells what this route is all about. Optional.
func (b *RouteBuilder) Filter(filter FilterFunction) *RouteBuilder
Filter appends a FilterFunction to the end of filters for this Route to build.
func (b *RouteBuilder) If(condition RouteSelectionConditionFunction) *RouteBuilder
If sets a condition function that controls matching the Route based on custom logic. The condition function is provided the HTTP request and should return true if the route should be considered.
Efficiency note: the condition function is called before checking the method, produces, and consumes criteria, so that the correct HTTP status code can be returned.
Lifecycle note: no filter functions have been called prior to calling the condition function, so the condition function should not depend on any context that might be set up by container or route filters.
func (b *RouteBuilder) Metadata(key string, value interface{}) *RouteBuilder
Metadata adds or updates a key=value pair to the metadata map.
func (b *RouteBuilder) Method(method string) *RouteBuilder
Method specifies what HTTP method to match. Required.
func (b *RouteBuilder) Notes(notes string) *RouteBuilder
Notes is a verbose explanation of the operation behavior. Optional.
func (b *RouteBuilder) Operation(name string) *RouteBuilder
Operation allows you to document what the actual method/function call is of the Route. Unless called, the operation name is derived from the RouteFunction set using To(..).
func (b *RouteBuilder) Param(parameter *Parameter) *RouteBuilder
Param allows you to document the parameters of the Route. It adds a new Parameter (does not check for duplicates).
func (b RouteBuilder) ParameterNamed(name string) (p *Parameter)
ParameterNamed returns a Parameter already known to the RouteBuilder. Returns nil if not. Use this to modify or extend information for the Parameter (through its Data()).
func (b *RouteBuilder) Path(subPath string) *RouteBuilder
Path specifies the relative (w.r.t WebService root path) URL path to match. Default is "/".
func (b *RouteBuilder) Produces(mimeTypes ...string) *RouteBuilder
Produces specifies what MIME types can be produced ; the matched one will appear in the Content-Type Http header.
func (b *RouteBuilder) Reads(sample interface{}, optionalDescription ...string) *RouteBuilder
Reads tells what resource type will be read from the request payload. Optional. A parameter of type "body" is added ,required is set to true and the dataType is set to the qualified name of the sample's type.
func (b *RouteBuilder) Returns(code int, message string, model interface{}) *RouteBuilder
Returns allows you to document what responses (errors or regular) can be expected. The model parameter is optional ; either pass a struct instance or use nil if not applicable.
func (b *RouteBuilder) ReturnsError(code int, message string, model interface{}) *RouteBuilder
ReturnsError is deprecated, use Returns instead.
func (b *RouteBuilder) ReturnsWithHeaders(code int, message string, model interface{}, headers map[string]Header) *RouteBuilder
ReturnsWithHeaders is similar to Returns, but can specify response headers
func (b *RouteBuilder) To(function RouteFunction) *RouteBuilder
To bind the route to a function. If this route is matched with the incoming Http Request then call this function with the *Request,*Response pair. Required.
func (b *RouteBuilder) Writes(samples ...interface{}) *RouteBuilder
Writes tells which one of the resource types will be written as the response payload. Optional.
RouteFunction declares the signature of a function that can be bound to a Route.
type RouteFunction func(*Request, *Response)
type RouteReader interface { Method() string Consumes() []string Path() string Doc() string Notes() string Operation() string ParameterDocs() []*Parameter // Returns a copy Metadata() map[string]interface{} Deprecated() bool }
RouteSelectionConditionFunction declares the signature of a function that can be used to add extra conditional logic when selecting whether the route matches the HTTP request.
type RouteSelectionConditionFunction func(httpRequest *http.Request) bool
A RouteSelector finds the best matching Route given the input HTTP Request RouteSelectors can optionally also implement the PathProcessor interface to also calculate the path parameters after the route has been selected.
type RouteSelector interface { // SelectRoute finds a Route given the input HTTP Request and a list of WebServices. // It returns a selected Route and its containing WebService or an error indicating // a problem. SelectRoute( webServices []*WebService, httpRequest *http.Request) (selectedService *WebService, selected *Route, err error) }
RouterJSR311 implements the flow for matching Requests to Routes (and consequently Resource Functions) as specified by the JSR311 http://jsr311.java.net/nonav/releases/1.1/spec/spec.html. RouterJSR311 implements the Router interface. Concept of locators is not implemented.
type RouterJSR311 struct{}
func (r RouterJSR311) ExtractParameters(route *Route, webService *WebService, urlPath string) map[string]string
ExtractParameters is used to obtain the path parameters from the route using the same matching engine as the JSR 311 router.
func (r RouterJSR311) SelectRoute( webServices []*WebService, httpRequest *http.Request) (selectedService *WebService, selectedRoute *Route, err error)
SelectRoute is part of the Router interface and returns the best match for the WebService and its Route for the given Request.
ServiceError is a transport object to pass information about a non-Http error occurred in a WebService while processing a request.
type ServiceError struct { Code int Message string Header http.Header }
▹ Example
func NewError(code int, message string) ServiceError
NewError returns a ServiceError using the code and reason
func NewErrorWithHeader(code int, message string, header http.Header) ServiceError
NewErrorWithHeader returns a ServiceError using the code, reason and header
func (s ServiceError) Error() string
Error returns a text representation of the service error
ServiceErrorHandleFunction declares functions that can be used to handle a service error situation. The first argument is the service error, the second is the request that resulted in the error and the third must be used to communicate an error response.
type ServiceErrorHandleFunction func(ServiceError, *Request, *Response)
SyncPoolCompessors is a CompressorProvider that use the standard sync.Pool.
type SyncPoolCompessors struct { GzipWriterPool *sync.Pool GzipReaderPool *sync.Pool ZlibWriterPool *sync.Pool }
func NewSyncPoolCompessors() *SyncPoolCompessors
NewSyncPoolCompessors returns a new ("empty") SyncPoolCompessors.
func (s *SyncPoolCompessors) AcquireGzipReader() *gzip.Reader
func (s *SyncPoolCompessors) AcquireGzipWriter() *gzip.Writer
func (s *SyncPoolCompessors) AcquireZlibWriter() *zlib.Writer
func (s *SyncPoolCompessors) ReleaseGzipReader(r *gzip.Reader)
func (s *SyncPoolCompessors) ReleaseGzipWriter(w *gzip.Writer)
func (s *SyncPoolCompessors) ReleaseZlibWriter(w *zlib.Writer)
TypeNameHandleFunction declares functions that can handle translating the name of a sample object into the restful documentation for the service.
type TypeNameHandleFunction func(sample interface{}) string
WebService holds a collection of Route values that bind a Http Method + URL Path to a function.
type WebService struct {
// contains filtered or unexported fields
}
func RegisteredWebServices() []*WebService
RegisteredWebServices returns the collections of WebServices from the DefaultContainer
func (w *WebService) ApiVersion(apiVersion string) *WebService
ApiVersion sets the API version for documentation purposes.
func (w *WebService) BodyParameter(name, description string) *Parameter
BodyParameter creates a new Parameter of kind Body for documentation purposes. It is initialized as required without a DataType.
func (w *WebService) Consumes(accepts ...string) *WebService
Consumes specifies that this WebService can consume one or more MIME types. Http requests must have one of these values set for the Content-Type header.
func (w *WebService) DELETE(subPath string) *RouteBuilder
DELETE is a shortcut for .Method("DELETE").Path(subPath)
func (w *WebService) Doc(plainText string) *WebService
Doc is used to set the documentation of this service.
func (w *WebService) Documentation() string
Documentation returns it.
func (w *WebService) Filter(filter FilterFunction) *WebService
Filter adds a filter function to the chain of filters applicable to all its Routes
func (w *WebService) FormParameter(name, description string) *Parameter
FormParameter creates a new Parameter of kind Form (using application/x-www-form-urlencoded) for documentation purposes. It is initialized as required with string as its DataType.
func (w *WebService) GET(subPath string) *RouteBuilder
GET is a shortcut for .Method("GET").Path(subPath)
func (w *WebService) HEAD(subPath string) *RouteBuilder
HEAD is a shortcut for .Method("HEAD").Path(subPath)
func (w *WebService) HeaderParameter(name, description string) *Parameter
HeaderParameter creates a new Parameter of kind (Http) Header for documentation purposes. It is initialized as not required with string as its DataType.
func (w *WebService) Method(httpMethod string) *RouteBuilder
Method creates a new RouteBuilder and initialize its http method
func (w *WebService) MultiPartFormParameter(name, description string) *Parameter
MultiPartFormParameter creates a new Parameter of kind Form (using multipart/form-data) for documentation purposes. It is initialized as required with string as its DataType.
func (w *WebService) OPTIONS(subPath string) *RouteBuilder
OPTIONS is a shortcut for .Method("OPTIONS").Path(subPath)
func (w *WebService) PATCH(subPath string) *RouteBuilder
PATCH is a shortcut for .Method("PATCH").Path(subPath)
func (w *WebService) POST(subPath string) *RouteBuilder
POST is a shortcut for .Method("POST").Path(subPath)
func (w *WebService) PUT(subPath string) *RouteBuilder
PUT is a shortcut for .Method("PUT").Path(subPath)
func (w *WebService) Param(parameter *Parameter) *WebService
Param adds a PathParameter to document parameters used in the root path.
func (w *WebService) Path(root string) *WebService
Path specifies the root URL template path of the WebService. All Routes will be relative to this path.
func (w *WebService) PathParameter(name, description string) *Parameter
PathParameter creates a new Parameter of kind Path for documentation purposes. It is initialized as required with string as its DataType.
func (w *WebService) PathParameters() []*Parameter
PathParameters return the path parameter names for (shared among its Routes)
func (w *WebService) Produces(contentTypes ...string) *WebService
Produces specifies that this WebService can produce one or more MIME types. Http requests must have one of these values set for the Accept header.
func (w *WebService) QueryParameter(name, description string) *Parameter
QueryParameter creates a new Parameter of kind Query for documentation purposes. It is initialized as not required with string as its DataType.
func (w *WebService) RemoveRoute(path, method string) error
RemoveRoute removes the specified route, looks for something that matches 'path' and 'method'
func (w *WebService) RootPath() string
RootPath returns the RootPath associated with this WebService. Default "/"
func (w *WebService) Route(builder *RouteBuilder) *WebService
Route creates a new Route using the RouteBuilder and add to the ordered list of Routes.
func (w *WebService) Routes() []Route
Routes returns the Routes associated with this WebService
func (w *WebService) SetDynamicRoutes(enable bool)
func (w *WebService) TypeNameHandler(handler TypeNameHandleFunction) *WebService
TypeNameHandler sets the function that will convert types to strings in the parameter and model definitions. If not set, the web service will invoke reflect.TypeOf(object).String().
func (w *WebService) Version() string
Version returns the API version for documentation purposes.