Documentation ¶
Overview ¶
Package restful , a lean package for creating REST-style WebServices without magic.
WebServices and Routes ¶
A WebService has a collection of Route objects that dispatch incoming Http Requests to a function calls. Typically, a WebService has a root path (e.g. /users) and defines common MIME types for its routes. WebServices must be added to a container (see below) in order to handler Http requests from a server.
A Route is defined by a HTTP method, an URL path and (optionally) the MIME types it consumes (Content-Type) and produces (Accept). This package has the logic to find the best matching Route and if found, call its Function.
ws := new(restful.WebService) ws. Path("/users"). Consumes(restful.MIME_JSON, restful.MIME_XML). Produces(restful.MIME_JSON, restful.MIME_XML) ws.Route(ws.GET("/{user-id}").To(u.findUser)) // u is a UserResource ... // GET http://localhost:8080/users/1 func (u UserResource) findUser(request *restful.Request, response *restful.Response) { id := request.PathParameter("user-id") ... }
The (*Request, *Response) arguments provide functions for reading information from the request and writing information back to the response.
See the example https://github.com/emicklei/go-restful/blob/master/examples/restful-user-resource.go with a full implementation.
Regular expression matching Routes ¶
A Route parameter can be specified using the format "uri/{var[:regexp]}" or the special version "uri/{var:*}" for matching the tail of the path. For example, /persons/{name:[A-Z][A-Z]} can be used to restrict values for the parameter "name" to only contain capital alphabetic characters. Regular expressions must use the standard Go syntax as described in the regexp package. (https://code.google.com/p/re2/wiki/Syntax) This feature requires the use of a CurlyRouter.
Containers ¶
A Container holds a collection of WebServices, Filters and a http.ServeMux for multiplexing http requests. Using the statements "restful.Add(...) and restful.Filter(...)" will register WebServices and Filters to the Default Container. The Default container of go-restful uses the http.DefaultServeMux. You can create your own Container and create a new http.Server for that particular container.
container := restful.NewContainer() server := &http.Server{Addr: ":8081", Handler: container}
Filters ¶
A filter dynamically intercepts requests and responses to transform or use the information contained in the requests or responses. You can use filters to perform generic logging, measurement, authentication, redirect, set response headers etc. In the restful package there are three hooks into the request,response flow where filters can be added. Each filter must define a FilterFunction:
func (req *restful.Request, resp *restful.Response, chain *restful.FilterChain)
Use the following statement to pass the request,response pair to the next filter or RouteFunction
chain.ProcessFilter(req, resp)
Container Filters ¶
These are processed before any registered WebService.
// install a (global) filter for the default container (processed before any webservice) restful.Filter(globalLogging)
WebService Filters ¶
These are processed before any Route of a WebService.
// install a webservice filter (processed before any route) ws.Filter(webserviceLogging).Filter(measureTime)
Route Filters ¶
These are processed before calling the function associated with the Route.
// install 2 chained route filters (processed before calling findUser) ws.Route(ws.GET("/{user-id}").Filter(routeLogging).Filter(NewCountFilter().routeCounter).To(findUser))
See the example https://github.com/emicklei/go-restful/blob/master/examples/restful-filters.go with full implementations.
Response Encoding ¶
Two encodings are supported: gzip and deflate. To enable this for all responses:
restful.DefaultContainer.EnableContentEncoding(true)
If a Http request includes the Accept-Encoding header then the response content will be compressed using the specified encoding. Alternatively, you can create a Filter that performs the encoding and install it per WebService or Route.
See the example https://github.com/emicklei/go-restful/blob/master/examples/restful-encoding-filter.go
OPTIONS support ¶
By installing a pre-defined container filter, your Webservice(s) can respond to the OPTIONS Http request.
Filter(OPTIONSFilter())
CORS ¶
By installing the filter of a CrossOriginResourceSharing (CORS), your WebService(s) can handle CORS requests.
cors := CrossOriginResourceSharing{ExposeHeaders: []string{"X-My-Header"}, CookiesAllowed: false, Container: DefaultContainer} Filter(cors.Filter)
Error Handling ¶
Unexpected things happen. If a request cannot be processed because of a failure, your service needs to tell via the response what happened and why. For this reason HTTP status codes exist and it is important to use the correct code in every exceptional situation.
400: Bad Request
If path or query parameters are not valid (content or type) then use http.StatusBadRequest.
404: Not Found
Despite a valid URI, the resource requested may not be available
500: Internal Server Error
If the application logic could not process the request (or write the response) then use http.StatusInternalServerError.
405: Method Not Allowed
The request has a valid URL but the method (GET,PUT,POST,...) is not allowed.
406: Not Acceptable
The request does not have or has an unknown Accept Header set for this operation.
415: Unsupported Media Type
The request does not have or has an unknown Content-Type Header set for this operation.
ServiceError ¶
In addition to setting the correct (error) Http status code, you can choose to write a ServiceError message on the response.
Performance options ¶
This package has several options that affect the performance of your service. It is important to understand them and how you can change it.
restful.DefaultContainer.DoNotRecover(false)
DoNotRecover controls whether panics will be caught to return HTTP 500. If set to false, the container will recover from panics. Default value is true
restful.SetCompressorProvider(NewBoundedCachedCompressors(20, 20))
If content encoding is enabled then the default strategy for getting new gzip/zlib writers and readers is to use a sync.Pool. Because writers are expensive structures, performance is even more improved when using a preloaded cache. You can also inject your own implementation.
Trouble shooting ¶
This package has the means to produce detail logging of the complete Http request matching process and filter invocation. Enabling this feature requires you to set an implementation of restful.StdLogger (e.g. log.Logger) instance such as:
restful.TraceLogger(log.New(os.Stdout, "[restful] ", log.LstdFlags|log.Lshortfile))
Logging ¶
The restful.SetLogger() method allows you to override the logger used by the package. By default restful uses the standard library `log` package and logs to stdout. Different logging packages are supported as long as they conform to `StdLogger` interface defined in the `log` sub-package, writing an adapter for your preferred package is simple.
Resources ¶
(c) 2012-2015, http://ernestmicklei.com. MIT License
Index ¶
- Constants
- Variables
- func Add(service *WebService)
- func DefaultRequestContentType(mime string)
- func DefaultResponseContentType(mime string)
- func EnableTracing(enabled bool)
- func Filter(filter FilterFunction)
- func NoBrowserCacheFilter(req *Request, resp *Response, chain *FilterChain)
- func RegisterEntityAccessor(mime string, erw EntityReaderWriter)
- func SetCompressorProvider(p CompressorProvider)
- func SetLogger(customLogger log.StdLogger)
- func TraceLogger(logger log.StdLogger)
- type BoundedCachedCompressors
- func (b *BoundedCachedCompressors) AcquireGzipReader() *gzip.Reader
- func (b *BoundedCachedCompressors) AcquireGzipWriter() *gzip.Writer
- func (b *BoundedCachedCompressors) AcquireZlibWriter() *zlib.Writer
- func (b *BoundedCachedCompressors) ReleaseGzipReader(r *gzip.Reader)
- func (b *BoundedCachedCompressors) ReleaseGzipWriter(w *gzip.Writer)
- func (b *BoundedCachedCompressors) ReleaseZlibWriter(w *zlib.Writer)
- type CollectionFormat
- type CompressingResponseWriter
- func (c *CompressingResponseWriter) Close() error
- func (c *CompressingResponseWriter) CloseNotify() <-chan bool
- func (c *CompressingResponseWriter) Header() http.Header
- func (c *CompressingResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
- func (c *CompressingResponseWriter) Write(bytes []byte) (int, error)
- func (c *CompressingResponseWriter) WriteHeader(status int)
- type CompressorProvider
- type Container
- func (c *Container) Add(service *WebService) *Container
- func (c *Container) Dispatch(httpWriter http.ResponseWriter, httpRequest *http.Request)
- func (c *Container) DoNotRecover(doNot bool)
- func (c *Container) EnableContentEncoding(enabled bool)
- func (c *Container) Filter(filter FilterFunction)
- func (c *Container) Handle(pattern string, handler http.Handler)
- func (c *Container) HandleWithFilter(pattern string, handler http.Handler)
- func (c *Container) OPTIONSFilter(req *Request, resp *Response, chain *FilterChain)
- func (c *Container) RecoverHandler(handler RecoverHandleFunction)
- func (c *Container) RegisteredWebServices() []*WebService
- func (c *Container) Remove(ws *WebService) error
- func (c *Container) Router(aRouter RouteSelector)
- func (c *Container) ServeHTTP(httpWriter http.ResponseWriter, httpRequest *http.Request)
- func (c *Container) ServiceErrorHandler(handler ServiceErrorHandleFunction)
- type CrossOriginResourceSharing
- type CurlyRouter
- type EntityReaderWriter
- type FilterChain
- type FilterFunction
- type Header
- type Items
- type Parameter
- func BodyParameter(name, description string) *Parameter
- func FormParameter(name, description string) *Parameter
- func HeaderParameter(name, description string) *Parameter
- func MultiPartFormParameter(name, description string) *Parameter
- func PathParameter(name, description string) *Parameter
- func QueryParameter(name, description string) *Parameter
- func (p *Parameter) AllowMultiple(multiple bool) *Parameter
- func (p *Parameter) AllowableValues(values map[string]string) *Parameter
- func (p *Parameter) CollectionFormat(format CollectionFormat) *Parameter
- func (p *Parameter) Data() ParameterData
- func (p *Parameter) DataFormat(formatName string) *Parameter
- func (p *Parameter) DataType(typeName string) *Parameter
- func (p *Parameter) DefaultValue(stringRepresentation string) *Parameter
- func (p *Parameter) Description(doc string) *Parameter
- func (p *Parameter) Kind() int
- func (p *Parameter) Required(required bool) *Parameter
- type ParameterData
- type PathProcessor
- type RecoverHandleFunction
- type Request
- func (r Request) Attribute(name string) interface{}
- func (r *Request) BodyParameter(name string) (string, error)
- func (r *Request) HeaderParameter(name string) string
- func (r *Request) PathParameter(name string) string
- func (r *Request) PathParameters() map[string]string
- func (r *Request) QueryParameter(name string) string
- func (r *Request) QueryParameters(name string) []string
- func (r *Request) ReadEntity(entityPointer interface{}) (err error)
- func (r Request) SelectedRoute() RouteReader
- func (r Request) SelectedRoutePath() string
- func (r *Request) SetAttribute(name string, value interface{})
- type Response
- func (r Response) AddHeader(header string, value string) Response
- func (r Response) CloseNotify() <-chan bool
- func (r Response) ContentLength() int
- func (r *Response) EntityWriter() (EntityReaderWriter, bool)
- func (r Response) Error() error
- func (r *Response) Flush()
- func (r *Response) Hijack() (net.Conn, *bufio.ReadWriter, error)
- func (r Response) InternalServerError() Response
- func (r *Response) PrettyPrint(bePretty bool)
- func (r *Response) SetRequestAccepts(mime string)
- func (r Response) StatusCode() int
- func (r *Response) Write(bytes []byte) (int, error)
- func (r *Response) WriteAsJson(value interface{}) error
- func (r *Response) WriteAsXml(value interface{}) error
- func (r *Response) WriteEntity(value interface{}) error
- func (r *Response) WriteError(httpStatus int, err error) (writeErr error)
- func (r *Response) WriteErrorString(httpStatus int, errorReason string) error
- func (r *Response) WriteHeader(httpStatus int)
- func (r *Response) WriteHeaderAndEntity(status int, value interface{}) error
- func (r *Response) WriteHeaderAndJson(status int, value interface{}, contentType string) error
- func (r *Response) WriteHeaderAndXml(status int, value interface{}) error
- func (r *Response) WriteJson(value interface{}, contentType string) error
- func (r *Response) WriteServiceError(httpStatus int, err ServiceError) error
- type ResponseError
- type Route
- type RouteBuilder
- func (b *RouteBuilder) AllowedMethodsWithoutContentType(methods []string) *RouteBuilder
- func (b *RouteBuilder) Build() Route
- func (b *RouteBuilder) Consumes(mimeTypes ...string) *RouteBuilder
- func (b *RouteBuilder) ContentEncodingEnabled(enabled bool) *RouteBuilder
- func (b *RouteBuilder) DefaultReturns(message string, model interface{}) *RouteBuilder
- func (b *RouteBuilder) Deprecate() *RouteBuilder
- func (b *RouteBuilder) Do(oneArgBlocks ...func(*RouteBuilder)) *RouteBuilder
- func (b *RouteBuilder) Doc(documentation string) *RouteBuilder
- func (b *RouteBuilder) Filter(filter FilterFunction) *RouteBuilder
- func (b *RouteBuilder) If(condition RouteSelectionConditionFunction) *RouteBuilder
- func (b *RouteBuilder) Metadata(key string, value interface{}) *RouteBuilder
- func (b *RouteBuilder) Method(method string) *RouteBuilder
- func (b *RouteBuilder) Notes(notes string) *RouteBuilder
- func (b *RouteBuilder) Operation(name string) *RouteBuilder
- func (b *RouteBuilder) Param(parameter *Parameter) *RouteBuilder
- func (b RouteBuilder) ParameterNamed(name string) (p *Parameter)
- func (b *RouteBuilder) Path(subPath string) *RouteBuilder
- func (b *RouteBuilder) Produces(mimeTypes ...string) *RouteBuilder
- func (b *RouteBuilder) Reads(sample interface{}, optionalDescription ...string) *RouteBuilder
- func (b *RouteBuilder) Returns(code int, message string, model interface{}) *RouteBuilder
- func (b *RouteBuilder) ReturnsError(code int, message string, model interface{}) *RouteBuilder
- func (b *RouteBuilder) ReturnsWithHeaders(code int, message string, model interface{}, headers map[string]Header) *RouteBuilder
- func (b *RouteBuilder) To(function RouteFunction) *RouteBuilder
- func (b *RouteBuilder) Writes(sample interface{}) *RouteBuilder
- type RouteFunction
- type RouteReader
- type RouteSelectionConditionFunction
- type RouteSelector
- type RouterJSR311
- type ServiceError
- type ServiceErrorHandleFunction
- type 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)
- type TypeNameHandleFunction
- type WebService
- func (w *WebService) ApiVersion(apiVersion string) *WebService
- func (w *WebService) BodyParameter(name, description string) *Parameter
- func (w *WebService) Consumes(accepts ...string) *WebService
- func (w *WebService) DELETE(subPath string) *RouteBuilder
- func (w *WebService) Doc(plainText string) *WebService
- func (w *WebService) Documentation() string
- func (w *WebService) Filter(filter FilterFunction) *WebService
- func (w *WebService) FormParameter(name, description string) *Parameter
- func (w *WebService) GET(subPath string) *RouteBuilder
- func (w *WebService) HEAD(subPath string) *RouteBuilder
- func (w *WebService) HeaderParameter(name, description string) *Parameter
- func (w *WebService) Method(httpMethod string) *RouteBuilder
- func (w *WebService) MultiPartFormParameter(name, description string) *Parameter
- func (w *WebService) OPTIONS(subPath string) *RouteBuilder
- func (w *WebService) PATCH(subPath string) *RouteBuilder
- func (w *WebService) POST(subPath string) *RouteBuilder
- func (w *WebService) PUT(subPath string) *RouteBuilder
- func (w *WebService) Param(parameter *Parameter) *WebService
- func (w *WebService) Path(root string) *WebService
- func (w *WebService) PathParameter(name, description string) *Parameter
- func (w *WebService) PathParameters() []*Parameter
- func (w *WebService) Produces(contentTypes ...string) *WebService
- func (w *WebService) QueryParameter(name, description string) *Parameter
- func (w *WebService) RemoveRoute(path, method string) error
- func (w *WebService) RootPath() string
- func (w *WebService) Route(builder *RouteBuilder) *WebService
- func (w *WebService) Routes() []Route
- func (w *WebService) SetDynamicRoutes(enable bool)
- func (w *WebService) TypeNameHandler(handler TypeNameHandleFunction) *WebService
- func (w *WebService) Version() string
Examples ¶
Constants ¶
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_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_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") )
Variables ¶
var ( MarshalIndent = json.MarshalIndent NewDecoder = json.NewDecoder NewEncoder = json.NewEncoder )
var DefaultResponseMimeType string
DefaultResponseMimeType is DEPRECATED, use DefaultResponseContentType(mime)
var DoNotRecover = false
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 EnableContentEncoding = false
OBSOLETE : use restful.DefaultContainer.EnableContentEncoding(true) to change this setting.
var PrettyPrintResponses = true
PrettyPrintResponses controls the indentation feature of XML and JSON serialization
Functions ¶
func Add ¶
func Add(service *WebService)
Add registers a new WebService add it to the DefaultContainer.
func DefaultRequestContentType ¶ added in v1.1.2
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 ¶ added in v1.1.2
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 ¶
func EnableTracing(enabled bool)
EnableTracing can be used to Trace logging on and off.
func Filter ¶
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 ¶
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 ¶
func RegisterEntityAccessor(mime string, erw EntityReaderWriter)
RegisterEntityAccessor add/overrides the ReaderWriter for encoding content with this MIME type.
func SetCompressorProvider ¶
func SetCompressorProvider(p CompressorProvider)
SetCompressorProvider sets the actual provider of compressors (zlib or gzip).
func TraceLogger ¶ added in v1.1.3
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.
Types ¶
type BoundedCachedCompressors ¶
type BoundedCachedCompressors struct {
// contains filtered or unexported fields
}
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.
Example ¶
// Register a compressor provider (gzip/deflate read/write) that uses // a bounded cache with a maximum of 20 writers and 20 readers. SetCompressorProvider(NewBoundedCachedCompressors(20, 20))
Output:
func NewBoundedCachedCompressors ¶
func NewBoundedCachedCompressors(writersCapacity, readersCapacity int) *BoundedCachedCompressors
NewBoundedCachedCompressors returns a new, with filled cache, BoundedCachedCompressors.
func (*BoundedCachedCompressors) AcquireGzipReader ¶
func (b *BoundedCachedCompressors) AcquireGzipReader() *gzip.Reader
AcquireGzipReader returns a *gzip.Reader. Needs to be released.
func (*BoundedCachedCompressors) AcquireGzipWriter ¶
func (b *BoundedCachedCompressors) AcquireGzipWriter() *gzip.Writer
AcquireGzipWriter returns an resettable *gzip.Writer. Needs to be released.
func (*BoundedCachedCompressors) AcquireZlibWriter ¶
func (b *BoundedCachedCompressors) AcquireZlibWriter() *zlib.Writer
AcquireZlibWriter returns an resettable *zlib.Writer. Needs to be released.
func (*BoundedCachedCompressors) ReleaseGzipReader ¶
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 (*BoundedCachedCompressors) ReleaseGzipWriter ¶
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 (*BoundedCachedCompressors) ReleaseZlibWriter ¶
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 ¶
type CollectionFormat string
func (CollectionFormat) String ¶
func (cf CollectionFormat) String() string
type CompressingResponseWriter ¶
type CompressingResponseWriter struct {
// contains filtered or unexported fields
}
CompressingResponseWriter is a http.ResponseWriter that can perform content encoding (gzip and zlib)
func NewCompressingResponseWriter ¶
func NewCompressingResponseWriter(httpWriter http.ResponseWriter, encoding string) (*CompressingResponseWriter, error)
NewCompressingResponseWriter create a CompressingResponseWriter for a known encoding = {gzip,deflate}
func (*CompressingResponseWriter) Close ¶
func (c *CompressingResponseWriter) Close() error
Close the underlying compressor
func (*CompressingResponseWriter) CloseNotify ¶
func (c *CompressingResponseWriter) CloseNotify() <-chan bool
CloseNotify is part of http.CloseNotifier interface
func (*CompressingResponseWriter) Header ¶
func (c *CompressingResponseWriter) Header() http.Header
Header is part of http.ResponseWriter interface
func (*CompressingResponseWriter) Hijack ¶
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 (*CompressingResponseWriter) Write ¶
func (c *CompressingResponseWriter) Write(bytes []byte) (int, error)
Write is part of http.ResponseWriter interface It is passed through the compressor
func (*CompressingResponseWriter) WriteHeader ¶
func (c *CompressingResponseWriter) WriteHeader(status int)
WriteHeader is part of http.ResponseWriter interface
type CompressorProvider ¶
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) }
CompressorProvider describes a component that can provider compressors for the std methods.
func CurrentCompressorProvider ¶
func CurrentCompressorProvider() CompressorProvider
CurrentCompressorProvider returns the current CompressorProvider. It is initialized using a SyncPoolCompessors.
type Container ¶
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
Example ¶
// The Default container of go-restful uses the http.DefaultServeMux. // You can create your own Container using restful.NewContainer() and create a new http.Server for that particular container ws := new(WebService) wsContainer := NewContainer() wsContainer.Add(ws) server := &http.Server{Addr: ":8080", Handler: wsContainer} server.ListenAndServe()
Output:
var DefaultContainer *Container
DefaultContainer is a restful.Container that uses http.DefaultServeMux
func NewContainer ¶
func NewContainer() *Container
NewContainer creates a new Container using a new ServeMux and default router (CurlyRouter)
func (*Container) Add ¶
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 (*Container) Dispatch ¶
func (c *Container) Dispatch(httpWriter http.ResponseWriter, httpRequest *http.Request)
Dispatch the incoming Http Request to a matching WebService.
func (*Container) DoNotRecover ¶
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 (*Container) EnableContentEncoding ¶
EnableContentEncoding (default=false) allows for GZIP or DEFLATE encoding of responses.
func (*Container) Filter ¶
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 (*Container) Handle ¶
Handle registers the handler for the given pattern. If a handler already exists for pattern, Handle panics.
func (*Container) HandleWithFilter ¶ added in v1.1.3
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 (*Container) OPTIONSFilter ¶
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 ¶
// Install the OPTIONS filter on a Container myContainer := new(Container) myContainer.Filter(myContainer.OPTIONSFilter)
Output:
func (*Container) RecoverHandler ¶
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 (*Container) RegisteredWebServices ¶
func (c *Container) RegisteredWebServices() []*WebService
RegisteredWebServices returns the collections of added WebServices
func (*Container) Remove ¶
func (c *Container) Remove(ws *WebService) error
func (*Container) Router ¶
func (c *Container) Router(aRouter RouteSelector)
Router changes the default Router (currently CurlyRouter)
func (*Container) ServeHTTP ¶
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 (*Container) ServiceErrorHandler ¶
func (c *Container) ServiceErrorHandler(handler ServiceErrorHandleFunction)
ServiceErrorHandler changes the default function (writeServiceError) to be called when a ServiceError is detected.
type CrossOriginResourceSharing ¶
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 }
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
Example ¶
// To install this filter on the Default Container use: cors := CrossOriginResourceSharing{ExposeHeaders: []string{"X-My-Header"}, CookiesAllowed: false, Container: DefaultContainer} Filter(cors.Filter)
Output:
func (CrossOriginResourceSharing) Filter ¶
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
type CurlyRouter ¶
type CurlyRouter struct{}
CurlyRouter expects Routes with paths that contain zero or more parameters in curly brackets.
func (CurlyRouter) SelectRoute ¶
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.
type EntityReaderWriter ¶
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 }
EntityReaderWriter can read and write values using an encoding such as JSON,XML.
func NewEntityAccessorJSON ¶
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 ¶
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.
type FilterChain ¶
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 }
FilterChain is a request scoped object to process one or more filters before calling the target RouteFunction.
func (*FilterChain) ProcessFilter ¶
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.
type FilterFunction ¶
type FilterFunction func(*Request, *Response, *FilterChain)
FilterFunction definitions must call ProcessFilter on the FilterChain to pass on the control and eventually call the RouteFunction
func OPTIONSFilter ¶
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 ¶
// Install the OPTIONS filter on the default Container Filter(OPTIONSFilter())
Output:
type Header ¶
Header describes a header for a response of the API
For more information: http://goo.gl/8us55a#headerObject
type Items ¶
type Items struct { Type string Format string Items *Items CollectionFormat string Default interface{} }
Items describe swagger simple schemas for headers
type Parameter ¶
type Parameter struct {
// contains filtered or unexported fields
}
Parameter is for documententing the parameter used in a Http Request ParameterData kinds are Path,Query and Body
func BodyParameter ¶
BodyParameter creates a new Parameter of kind Body for documentation purposes. It is initialized as required without a DataType.
func FormParameter ¶
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 ¶
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 ¶
func PathParameter ¶
PathParameter creates a new Parameter of kind Path for documentation purposes. It is initialized as required with string as its DataType.
func QueryParameter ¶
QueryParameter creates a new Parameter of kind Query for documentation purposes. It is initialized as not required with string as its DataType.
func (*Parameter) AllowMultiple ¶
AllowMultiple sets the allowMultiple field and returns the receiver
func (*Parameter) AllowableValues ¶
AllowableValues sets the allowableValues field and returns the receiver
func (*Parameter) CollectionFormat ¶
func (p *Parameter) CollectionFormat(format CollectionFormat) *Parameter
CollectionFormat sets the collection format for an array type
func (*Parameter) Data ¶
func (p *Parameter) Data() ParameterData
Data returns the state of the Parameter
func (*Parameter) DataFormat ¶
DataFormat sets the dataFormat field for Swagger UI
func (*Parameter) DefaultValue ¶
DefaultValue sets the default value field and returns the receiver
func (*Parameter) Description ¶
Description sets the description value field and returns the receiver
type ParameterData ¶
type ParameterData struct {
Name, Description, DataType, DataFormat string
Kind int
Required bool
AllowableValues map[string]string
AllowMultiple bool
DefaultValue string
CollectionFormat string
}
ParameterData represents the state of a Parameter. It is made public to make it accessible to e.g. the Swagger package.
type PathProcessor ¶
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 }
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 RecoverHandleFunction ¶
type RecoverHandleFunction func(interface{}, http.ResponseWriter)
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 Request ¶
Request is a wrapper for a http Request that provides convenience methods
func NewRequest ¶ added in v1.1.0
func (Request) Attribute ¶
Attribute returns the value associated to the given name. Returns nil if absent.
func (*Request) BodyParameter ¶
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 (*Request) HeaderParameter ¶
HeaderParameter returns the HTTP Header value of a Header name or empty if missing
func (*Request) PathParameter ¶
PathParameter accesses the Path parameter value by its name
func (*Request) PathParameters ¶
PathParameters accesses the Path parameter values
func (*Request) QueryParameter ¶
QueryParameter returns the (first) Query parameter value by its name
func (*Request) QueryParameters ¶
QueryParameters returns the all the query parameters values by name
func (*Request) ReadEntity ¶
ReadEntity checks the Accept header and reads the content into the entityPointer.
func (Request) SelectedRoute ¶
func (r Request) SelectedRoute() RouteReader
SelectedRoute return the Route that selected by the container
func (Request) SelectedRoutePath ¶
SelectedRoutePath root path + route path that matched the request, e.g. /meetings/{id}/attendees
func (*Request) SetAttribute ¶
SetAttribute adds or replaces the attribute with the given value.
type Response ¶
type Response struct { http.ResponseWriter // contains filtered or unexported fields }
Response is a wrapper on the actual http ResponseWriter It provides several convenience methods to prepare and write response content.
func NewResponse ¶
func NewResponse(httpWriter http.ResponseWriter) *Response
NewResponse creates a new response based on a http ResponseWriter.
func (Response) CloseNotify ¶
CloseNotify is part of http.CloseNotifier interface
func (Response) ContentLength ¶
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 (*Response) EntityWriter ¶
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 (*Response) Flush ¶
func (r *Response) Flush()
Flush implements http.Flusher interface, which sends any buffered data to the client.
func (*Response) Hijack ¶
Hijack implements the http.Hijacker interface. This expands the Response to fulfill http.Hijacker if the underlying http.ResponseWriter supports it.
func (Response) InternalServerError ¶
InternalServerError writes the StatusInternalServerError header. DEPRECATED, use WriteErrorString(http.StatusInternalServerError,reason)
func (*Response) PrettyPrint ¶ added in v1.1.3
PrettyPrint changes whether this response must produce pretty (line-by-line, indented) JSON or XML output.
func (*Response) SetRequestAccepts ¶ added in v1.1.3
SetRequestAccepts tells the response what Mime-type(s) the HTTP request said it wants to accept. Exposed for testing.
func (Response) StatusCode ¶
StatusCode returns the code that has been written using WriteHeader.
func (*Response) Write ¶
Write writes the data to the connection as part of an HTTP reply. Write is part of http.ResponseWriter interface.
func (*Response) WriteAsJson ¶
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 (*Response) WriteAsXml ¶
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 (*Response) WriteEntity ¶
WriteEntity calls WriteHeaderAndEntity with Http Status OK (200)
func (*Response) WriteError ¶
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 (*Response) WriteErrorString ¶
WriteErrorString is a convenience method for an error status with the actual error
func (*Response) WriteHeader ¶
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 (*Response) WriteHeaderAndEntity ¶
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 (*Response) WriteHeaderAndJson ¶
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 (*Response) WriteHeaderAndXml ¶
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 (*Response) WriteJson ¶
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 (*Response) WriteServiceError ¶
func (r *Response) WriteServiceError(httpStatus int, err ServiceError) error
WriteServiceError is a convenience method for a responding with a status and a ServiceError
type ResponseError ¶ added in v1.1.3
type ResponseError struct { Code int Message string Model interface{} Headers map[string]Header IsDefault bool }
ResponseError represents a response; not necessarily an error.
type Route ¶
type Route struct { 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 // 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 }
Route binds a HTTP Method,Path,Consumes combination to a RouteFunction.
func (Route) EnableContentEncoding ¶
EnableContentEncoding (default=false) allows for GZIP or DEFLATE encoding of responses. Overrides the container.contentEncodingEnabled value.
type RouteBuilder ¶
type RouteBuilder struct {
// contains filtered or unexported fields
}
RouteBuilder is a helper to construct Routes.
func (*RouteBuilder) AllowedMethodsWithoutContentType ¶
func (b *RouteBuilder) AllowedMethodsWithoutContentType(methods []string) *RouteBuilder
AllowedMethodsWithoutContentType overides 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 (*RouteBuilder) Build ¶
func (b *RouteBuilder) Build() Route
Build creates a new Route using the specification details collected by the RouteBuilder
func (*RouteBuilder) Consumes ¶
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 (*RouteBuilder) ContentEncodingEnabled ¶
func (b *RouteBuilder) ContentEncodingEnabled(enabled bool) *RouteBuilder
ContentEncodingEnabled allows you to override the Containers value for auto-compressing this route response.
func (*RouteBuilder) DefaultReturns ¶
func (b *RouteBuilder) DefaultReturns(message string, model interface{}) *RouteBuilder
DefaultReturns is a special Returns call that sets the default of the response.
func (*RouteBuilder) Deprecate ¶
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 (*RouteBuilder) Do ¶ added in v1.1.3
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 (*RouteBuilder) Doc ¶
func (b *RouteBuilder) Doc(documentation string) *RouteBuilder
Doc tells what this route is all about. Optional.
func (*RouteBuilder) Filter ¶
func (b *RouteBuilder) Filter(filter FilterFunction) *RouteBuilder
Filter appends a FilterFunction to the end of filters for this Route to build.
func (*RouteBuilder) If ¶
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 (*RouteBuilder) Metadata ¶
func (b *RouteBuilder) Metadata(key string, value interface{}) *RouteBuilder
Metadata adds or updates a key=value pair to the metadata map.
func (*RouteBuilder) Method ¶
func (b *RouteBuilder) Method(method string) *RouteBuilder
Method specifies what HTTP method to match. Required.
func (*RouteBuilder) Notes ¶ added in v1.1.3
func (b *RouteBuilder) Notes(notes string) *RouteBuilder
Notes is a verbose explanation of the operation behavior. Optional.
func (*RouteBuilder) Operation ¶
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 (*RouteBuilder) Param ¶
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 (RouteBuilder) ParameterNamed ¶ added in v1.1.2
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 (*RouteBuilder) Path ¶
func (b *RouteBuilder) Path(subPath string) *RouteBuilder
Path specifies the relative (w.r.t WebService root path) URL path to match. Default is "/".
func (*RouteBuilder) Produces ¶
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 (*RouteBuilder) Reads ¶
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 (*RouteBuilder) Returns ¶ added in v1.1.3
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 (*RouteBuilder) ReturnsError ¶ added in v1.1.3
func (b *RouteBuilder) ReturnsError(code int, message string, model interface{}) *RouteBuilder
ReturnsError is deprecated, use Returns instead.
func (*RouteBuilder) ReturnsWithHeaders ¶
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 (*RouteBuilder) To ¶
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 (*RouteBuilder) Writes ¶
func (b *RouteBuilder) Writes(sample interface{}) *RouteBuilder
Writes tells what resource type will be written as the response payload. Optional.
type RouteFunction ¶
RouteFunction declares the signature of a function that can be bound to a Route.
type RouteReader ¶
type RouteSelectionConditionFunction ¶
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 RouteSelector ¶
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) }
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 RouterJSR311 ¶
type RouterJSR311 struct{}
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.
func (RouterJSR311) ExtractParameters ¶
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 (RouterJSR311) SelectRoute ¶
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.
type ServiceError ¶
ServiceError is a transport object to pass information about a non-Http error occurred in a WebService while processing a request.
Example ¶
resp := new(Response) resp.WriteEntity(NewError(http.StatusBadRequest, "Non-integer {id} path parameter"))
Output:
func NewError ¶
func NewError(code int, message string) ServiceError
NewError returns a ServiceError using the code and reason
func NewErrorWithHeader ¶
func NewErrorWithHeader(code int, message string, header http.Header) ServiceError
NewErrorWithHeader returns a ServiceError using the code, reason and header
func (ServiceError) Error ¶
func (s ServiceError) Error() string
Error returns a text representation of the service error
type ServiceErrorHandleFunction ¶
type ServiceErrorHandleFunction func(ServiceError, *Request, *Response)
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 SyncPoolCompessors ¶
type SyncPoolCompessors struct { GzipWriterPool *sync.Pool GzipReaderPool *sync.Pool ZlibWriterPool *sync.Pool }
SyncPoolCompessors is a CompressorProvider that use the standard sync.Pool.
func NewSyncPoolCompessors ¶
func NewSyncPoolCompessors() *SyncPoolCompessors
NewSyncPoolCompessors returns a new ("empty") SyncPoolCompessors.
func (*SyncPoolCompessors) AcquireGzipReader ¶
func (s *SyncPoolCompessors) AcquireGzipReader() *gzip.Reader
func (*SyncPoolCompessors) AcquireGzipWriter ¶
func (s *SyncPoolCompessors) AcquireGzipWriter() *gzip.Writer
func (*SyncPoolCompessors) AcquireZlibWriter ¶
func (s *SyncPoolCompessors) AcquireZlibWriter() *zlib.Writer
func (*SyncPoolCompessors) ReleaseGzipReader ¶
func (s *SyncPoolCompessors) ReleaseGzipReader(r *gzip.Reader)
func (*SyncPoolCompessors) ReleaseGzipWriter ¶
func (s *SyncPoolCompessors) ReleaseGzipWriter(w *gzip.Writer)
func (*SyncPoolCompessors) ReleaseZlibWriter ¶
func (s *SyncPoolCompessors) ReleaseZlibWriter(w *zlib.Writer)
type TypeNameHandleFunction ¶
type TypeNameHandleFunction func(sample interface{}) string
TypeNameHandleFunction declares functions that can handle translating the name of a sample object into the restful documentation for the service.
type WebService ¶
type WebService struct {
// contains filtered or unexported fields
}
WebService holds a collection of Route values that bind a Http Method + URL Path to a function.
func RegisteredWebServices ¶
func RegisteredWebServices() []*WebService
RegisteredWebServices returns the collections of WebServices from the DefaultContainer
func (*WebService) ApiVersion ¶ added in v1.1.3
func (w *WebService) ApiVersion(apiVersion string) *WebService
ApiVersion sets the API version for documentation purposes.
func (*WebService) BodyParameter ¶
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 (*WebService) Consumes ¶
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 (*WebService) DELETE ¶
func (w *WebService) DELETE(subPath string) *RouteBuilder
DELETE is a shortcut for .Method("DELETE").Path(subPath)
func (*WebService) Doc ¶
func (w *WebService) Doc(plainText string) *WebService
Doc is used to set the documentation of this service.
func (*WebService) Documentation ¶
func (w *WebService) Documentation() string
Documentation returns it.
func (*WebService) Filter ¶
func (w *WebService) Filter(filter FilterFunction) *WebService
Filter adds a filter function to the chain of filters applicable to all its Routes
func (*WebService) FormParameter ¶
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 (*WebService) GET ¶
func (w *WebService) GET(subPath string) *RouteBuilder
GET is a shortcut for .Method("GET").Path(subPath)
func (*WebService) HEAD ¶
func (w *WebService) HEAD(subPath string) *RouteBuilder
HEAD is a shortcut for .Method("HEAD").Path(subPath)
func (*WebService) HeaderParameter ¶
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 (*WebService) Method ¶
func (w *WebService) Method(httpMethod string) *RouteBuilder
Method creates a new RouteBuilder and initialize its http method
func (*WebService) MultiPartFormParameter ¶
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 (*WebService) OPTIONS ¶
func (w *WebService) OPTIONS(subPath string) *RouteBuilder
OPTIONS is a shortcut for .Method("OPTIONS").Path(subPath)
func (*WebService) PATCH ¶
func (w *WebService) PATCH(subPath string) *RouteBuilder
PATCH is a shortcut for .Method("PATCH").Path(subPath)
func (*WebService) POST ¶
func (w *WebService) POST(subPath string) *RouteBuilder
POST is a shortcut for .Method("POST").Path(subPath)
func (*WebService) PUT ¶
func (w *WebService) PUT(subPath string) *RouteBuilder
PUT is a shortcut for .Method("PUT").Path(subPath)
func (*WebService) Param ¶
func (w *WebService) Param(parameter *Parameter) *WebService
Param adds a PathParameter to document parameters used in the root path.
func (*WebService) 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 (*WebService) PathParameter ¶
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 (*WebService) PathParameters ¶
func (w *WebService) PathParameters() []*Parameter
PathParameters return the path parameter names for (shared among its Routes)
func (*WebService) Produces ¶
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 (*WebService) QueryParameter ¶
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 (*WebService) RemoveRoute ¶
func (w *WebService) RemoveRoute(path, method string) error
RemoveRoute removes the specified route, looks for something that matches 'path' and 'method'
func (*WebService) RootPath ¶
func (w *WebService) RootPath() string
RootPath returns the RootPath associated with this WebService. Default "/"
func (*WebService) Route ¶
func (w *WebService) Route(builder *RouteBuilder) *WebService
Route creates a new Route using the RouteBuilder and add to the ordered list of Routes.
func (*WebService) Routes ¶
func (w *WebService) Routes() []Route
Routes returns the Routes associated with this WebService
func (*WebService) SetDynamicRoutes ¶
func (w *WebService) SetDynamicRoutes(enable bool)
func (*WebService) TypeNameHandler ¶
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 (*WebService) Version ¶ added in v1.1.3
func (w *WebService) Version() string
Version returns the API version for documentation purposes.
Source Files ¶
- compress.go
- compressor_cache.go
- compressor_pools.go
- compressors.go
- constants.go
- container.go
- cors_filter.go
- curly.go
- curly_route.go
- custom_verb.go
- doc.go
- entity_accessors.go
- filter.go
- json.go
- jsr311.go
- logger.go
- mime.go
- options_filter.go
- parameter.go
- path_expression.go
- path_processor.go
- request.go
- response.go
- route.go
- route_builder.go
- route_reader.go
- router.go
- service_error.go
- web_service.go
- web_service_container.go
Directories ¶
Path | Synopsis |
---|---|
examples
|
|
basicauth
Module
|
|
cors
Module
|
|
cpuprof
Module
|
|
encoding
Module
|
|
filters
Module
|
|
form
Module
|
|
form-httpin
Module
|
|
fulllog
Module
|
|
google-custom-method
Module
|
|
hello
Module
|
|
jwtauth
Module
|
|
multi-container
Module
|
|
ncsa
Module
|
|
nocache
Module
|
|
openapi
Module
|
|
template
Module
|
|
user-resource
Module
|
|