go-restful: github.com/emicklei/go-restful Index | Examples | Files | Directories

package restful

import "github.com/emicklei/go-restful"

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

[project]: https://github.com/emicklei/go-restful

[examples]: https://github.com/emicklei/go-restful/blob/master/examples

[design]: http://ernestmicklei.com/2012/11/11/go-restful-api-design/

[showcases]: https://github.com/emicklei/mora, https://github.com/emicklei/landskape

(c) 2012-2015, http://ernestmicklei.com. MIT License

Index

Examples

Package 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 router.go service_error.go web_service.go web_service_container.go

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

    // 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

func Add Uses

func Add(service *WebService)

Add registers a new WebService add it to the DefaultContainer.

func DefaultRequestContentType Uses

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 Uses

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 Uses

func EnableTracing(enabled bool)

EnableTracing can be used to Trace logging on and off.

func Filter Uses

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 Uses

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 Uses

func RegisterEntityAccessor(mime string, erw EntityReaderWriter)

RegisterEntityAccessor add/overrides the ReaderWriter for encoding content with this MIME type.

func SetCompressorProvider Uses

func SetCompressorProvider(p CompressorProvider)

SetCompressorProvider sets the actual provider of compressors (zlib or gzip).

func SetLogger Uses

func SetLogger(customLogger log.StdLogger)

SetLogger exposes the setter for the global logger on the top-level package

func TraceLogger Uses

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.

type BoundedCachedCompressors Uses

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.

Code:

// 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))

func NewBoundedCachedCompressors Uses

func NewBoundedCachedCompressors(writersCapacity, readersCapacity int) *BoundedCachedCompressors

NewBoundedCachedCompressors returns a new, with filled cache, BoundedCachedCompressors.

func (*BoundedCachedCompressors) AcquireGzipReader Uses

func (b *BoundedCachedCompressors) AcquireGzipReader() *gzip.Reader

AcquireGzipReader returns a *gzip.Reader. Needs to be released.

func (*BoundedCachedCompressors) AcquireGzipWriter Uses

func (b *BoundedCachedCompressors) AcquireGzipWriter() *gzip.Writer

AcquireGzipWriter returns an resettable *gzip.Writer. Needs to be released.

func (*BoundedCachedCompressors) AcquireZlibWriter Uses

func (b *BoundedCachedCompressors) AcquireZlibWriter() *zlib.Writer

AcquireZlibWriter returns an resettable *zlib.Writer. Needs to be released.

func (*BoundedCachedCompressors) ReleaseGzipReader Uses

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 Uses

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 Uses

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 Uses

type CollectionFormat string

func (CollectionFormat) String Uses

func (cf CollectionFormat) String() string

type CompressingResponseWriter Uses

type CompressingResponseWriter struct {
    // contains filtered or unexported fields
}

CompressingResponseWriter is a http.ResponseWriter that can perform content encoding (gzip and zlib)

func NewCompressingResponseWriter Uses

func NewCompressingResponseWriter(httpWriter http.ResponseWriter, encoding string) (*CompressingResponseWriter, error)

NewCompressingResponseWriter create a CompressingResponseWriter for a known encoding = {gzip,deflate}

func (*CompressingResponseWriter) Close Uses

func (c *CompressingResponseWriter) Close() error

Close the underlying compressor

func (*CompressingResponseWriter) CloseNotify Uses

func (c *CompressingResponseWriter) CloseNotify() <-chan bool

CloseNotify is part of http.CloseNotifier interface

func (*CompressingResponseWriter) Header Uses

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

Header is part of http.ResponseWriter interface

func (*CompressingResponseWriter) Hijack Uses

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 Uses

func (c *CompressingResponseWriter) Write(bytes []byte) (int, error)

Write is part of http.ResponseWriter interface It is passed through the compressor

func (*CompressingResponseWriter) WriteHeader Uses

func (c *CompressingResponseWriter) WriteHeader(status int)

WriteHeader is part of http.ResponseWriter interface

type CompressorProvider Uses

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 Uses

func CurrentCompressorProvider() CompressorProvider

CurrentCompressorProvider returns the current CompressorProvider. It is initialized using a SyncPoolCompessors.

type Container Uses

type Container struct {
    ServeMux *http.ServeMux
    // contains filtered or unexported fields
}

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

var DefaultContainer *Container

DefaultContainer is a restful.Container that uses http.DefaultServeMux

Code:

// 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()

func NewContainer Uses

func NewContainer() *Container

NewContainer creates a new Container using a new ServeMux and default router (CurlyRouter)

func (*Container) Add Uses

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 Uses

func (c *Container) Dispatch(httpWriter http.ResponseWriter, httpRequest *http.Request)

Dispatch the incoming Http Request to a matching WebService.

func (*Container) DoNotRecover Uses

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 (*Container) EnableContentEncoding Uses

func (c *Container) EnableContentEncoding(enabled bool)

EnableContentEncoding (default=false) allows for GZIP or DEFLATE encoding of responses.

func (*Container) Filter Uses

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 Uses

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 (*Container) HandleWithFilter Uses

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 (*Container) OPTIONSFilter Uses

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).

Code:

// Install the OPTIONS filter on a Container
myContainer := new(Container)
myContainer.Filter(myContainer.OPTIONSFilter)

func (*Container) RecoverHandler Uses

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 Uses

func (c *Container) RegisteredWebServices() []*WebService

RegisteredWebServices returns the collections of added WebServices

func (*Container) Remove Uses

func (c *Container) Remove(ws *WebService) error

func (*Container) Router Uses

func (c *Container) Router(aRouter RouteSelector)

Router changes the default Router (currently CurlyRouter)

func (*Container) ServeHTTP Uses

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 Uses

func (c *Container) ServiceErrorHandler(handler ServiceErrorHandleFunction)

ServiceErrorHandler changes the default function (writeServiceError) to be called when a ServiceError is detected.

type CrossOriginResourceSharing Uses

type CrossOriginResourceSharing struct {
    ExposeHeaders  []string // list of Header names
    AllowedHeaders []string // list of Header names
    AllowedDomains []string // list of allowed values for Http Origin. An allowed value can be a regular expression to support subdomain matching. If empty all are allowed.
    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

Code:

// To install this filter on the Default Container use:
cors := CrossOriginResourceSharing{ExposeHeaders: []string{"X-My-Header"}, CookiesAllowed: false, Container: DefaultContainer}
Filter(cors.Filter)

func (CrossOriginResourceSharing) Filter Uses

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 Uses

type CurlyRouter struct{}

CurlyRouter expects Routes with paths that contain zero or more parameters in curly brackets.

func (CurlyRouter) SelectRoute Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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).

Code:

// Install the OPTIONS filter on the default Container
Filter(OPTIONSFilter())

type Parameter Uses

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 Uses

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 Uses

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 Uses

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 PathParameter Uses

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 Uses

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 (*Parameter) AllowMultiple Uses

func (p *Parameter) AllowMultiple(multiple bool) *Parameter

AllowMultiple sets the allowMultiple field and returns the receiver

func (*Parameter) AllowableValues Uses

func (p *Parameter) AllowableValues(values map[string]string) *Parameter

AllowableValues sets the allowableValues field and returns the receiver

func (*Parameter) CollectionFormat Uses

func (p *Parameter) CollectionFormat(format CollectionFormat) *Parameter

CollectionFormat sets the collection format for an array type

func (*Parameter) Data Uses

func (p *Parameter) Data() ParameterData

Data returns the state of the Parameter

func (*Parameter) DataFormat Uses

func (p *Parameter) DataFormat(formatName string) *Parameter

DataFormat sets the dataFormat field for Swagger UI

func (*Parameter) DataType Uses

func (p *Parameter) DataType(typeName string) *Parameter

DataType sets the dataType field and returns the receiver

func (*Parameter) DefaultValue Uses

func (p *Parameter) DefaultValue(stringRepresentation string) *Parameter

DefaultValue sets the default value field and returns the receiver

func (*Parameter) Description Uses

func (p *Parameter) Description(doc string) *Parameter

Description sets the description value field and returns the receiver

func (*Parameter) Kind Uses

func (p *Parameter) Kind() int

Kind returns the parameter type indicator (see const for valid values)

func (*Parameter) Required Uses

func (p *Parameter) Required(required bool) *Parameter

Required sets the required field and returns the receiver

type ParameterData Uses

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 Uses

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 Uses

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 Uses

type Request struct {
    Request *http.Request
    // contains filtered or unexported fields
}

Request is a wrapper for a http Request that provides convenience methods

func NewRequest Uses

func NewRequest(httpRequest *http.Request) *Request

func (Request) Attribute Uses

func (r Request) Attribute(name string) interface{}

Attribute returns the value associated to the given name. Returns nil if absent.

func (*Request) BodyParameter Uses

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 (*Request) HeaderParameter Uses

func (r *Request) HeaderParameter(name string) string

HeaderParameter returns the HTTP Header value of a Header name or empty if missing

func (*Request) PathParameter Uses

func (r *Request) PathParameter(name string) string

PathParameter accesses the Path parameter value by its name

func (*Request) PathParameters Uses

func (r *Request) PathParameters() map[string]string

PathParameters accesses the Path parameter values

func (*Request) QueryParameter Uses

func (r *Request) QueryParameter(name string) string

QueryParameter returns the (first) Query parameter value by its name

func (*Request) QueryParameters Uses

func (r *Request) QueryParameters(name string) []string

QueryParameters returns the all the query parameters values by name

func (*Request) ReadEntity Uses

func (r *Request) ReadEntity(entityPointer interface{}) (err error)

ReadEntity checks the Accept header and reads the content into the entityPointer.

func (Request) SelectedRoutePath Uses

func (r Request) SelectedRoutePath() string

SelectedRoutePath root path + route path that matched the request, e.g. /meetings/{id}/attendees

func (*Request) SetAttribute Uses

func (r *Request) SetAttribute(name string, value interface{})

SetAttribute adds or replaces the attribute with the given value.

type Response Uses

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 Uses

func NewResponse(httpWriter http.ResponseWriter) *Response

NewResponse creates a new response based on a http ResponseWriter.

func (Response) AddHeader Uses

func (r Response) AddHeader(header string, value string) Response

AddHeader is a shortcut for .Header().Add(header,value)

func (Response) CloseNotify Uses

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

CloseNotify is part of http.CloseNotifier interface

func (Response) ContentLength Uses

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 (*Response) EntityWriter Uses

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) Error Uses

func (r Response) Error() error

Error returns the err created by WriteError

func (*Response) Flush Uses

func (r *Response) Flush()

Flush implements http.Flusher interface, which sends any buffered data to the client.

func (*Response) Hijack Uses

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 (Response) InternalServerError Uses

func (r Response) InternalServerError() Response

InternalServerError writes the StatusInternalServerError header. DEPRECATED, use WriteErrorString(http.StatusInternalServerError,reason)

func (*Response) PrettyPrint Uses

func (r *Response) PrettyPrint(bePretty bool)

PrettyPrint changes whether this response must produce pretty (line-by-line, indented) JSON or XML output.

func (*Response) SetRequestAccepts Uses

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 (Response) StatusCode Uses

func (r Response) StatusCode() int

StatusCode returns the code that has been written using WriteHeader.

func (*Response) Write Uses

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 (*Response) WriteAsJson Uses

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 (*Response) WriteAsXml Uses

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 (*Response) WriteEntity Uses

func (r *Response) WriteEntity(value interface{}) error

WriteEntity calls WriteHeaderAndEntity with Http Status OK (200)

func (*Response) WriteError Uses

func (r *Response) WriteError(httpStatus int, err error) error

WriteError write the http status and the error string on the response. err can be nil.

func (*Response) WriteErrorString Uses

func (r *Response) WriteErrorString(httpStatus int, errorReason string) error

WriteErrorString is a convenience method for an error status with the actual error

func (*Response) WriteHeader Uses

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 (*Response) WriteHeaderAndEntity Uses

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 (*Response) WriteHeaderAndJson Uses

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 (*Response) WriteHeaderAndXml Uses

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 (*Response) WriteJson Uses

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 (*Response) WriteServiceError Uses

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 Uses

type ResponseError struct {
    Code      int
    Message   string
    Model     interface{}
    IsDefault bool
}

ResponseError represents a response; not necessarily an error.

type Route Uses

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 Uses

func (r Route) EnableContentEncoding(enabled bool)

EnableContentEncoding (default=false) allows for GZIP or DEFLATE encoding of responses. Overrides the container.contentEncodingEnabled value.

func (Route) String Uses

func (r Route) String() string

for debugging

type RouteBuilder Uses

type RouteBuilder struct {
    // contains filtered or unexported fields
}

RouteBuilder is a helper to construct Routes.

func (*RouteBuilder) Build Uses

func (b *RouteBuilder) Build() Route

Build creates a new Route using the specification details collected by the RouteBuilder

func (*RouteBuilder) Consumes Uses

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 Uses

func (b *RouteBuilder) ContentEncodingEnabled(enabled bool) *RouteBuilder

ContentEncodingEnabled allows you to override the Containers value for auto-compressing this route response.

func (*RouteBuilder) DefaultReturns Uses

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 Uses

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 Uses

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 Uses

func (b *RouteBuilder) Doc(documentation string) *RouteBuilder

Doc tells what this route is all about. Optional.

func (*RouteBuilder) Filter Uses

func (b *RouteBuilder) Filter(filter FilterFunction) *RouteBuilder

Filter appends a FilterFunction to the end of filters for this Route to build.

func (*RouteBuilder) If Uses

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 Uses

func (b *RouteBuilder) Metadata(key string, value interface{}) *RouteBuilder

Metadata adds or updates a key=value pair to the metadata map.

func (*RouteBuilder) Method Uses

func (b *RouteBuilder) Method(method string) *RouteBuilder

Method specifies what HTTP method to match. Required.

func (*RouteBuilder) Notes Uses

func (b *RouteBuilder) Notes(notes string) *RouteBuilder

Notes is a verbose explanation of the operation behavior. Optional.

func (*RouteBuilder) Operation Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

func (b *RouteBuilder) ReturnsError(code int, message string, model interface{}) *RouteBuilder

ReturnsError is deprecated, use Returns instead.

func (*RouteBuilder) To Uses

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 Uses

func (b *RouteBuilder) Writes(sample interface{}) *RouteBuilder

Writes tells what resource type will be written as the response payload. Optional.

type RouteFunction Uses

type RouteFunction func(*Request, *Response)

RouteFunction declares the signature of a function that can be bound to a Route.

type RouteSelectionConditionFunction Uses

type RouteSelectionConditionFunction func(httpRequest *http.Request) 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 RouteSelector Uses

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 Uses

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 Uses

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 Uses

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 Uses

type ServiceError struct {
    Code    int
    Message string
}

ServiceError is a transport object to pass information about a non-Http error occurred in a WebService while processing a request.

Code:

resp := new(Response)
resp.WriteEntity(NewError(http.StatusBadRequest, "Non-integer {id} path parameter"))

func NewError Uses

func NewError(code int, message string) ServiceError

NewError returns a ServiceError using the code and reason

func (ServiceError) Error Uses

func (s ServiceError) Error() string

Error returns a text representation of the service error

type ServiceErrorHandleFunction Uses

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 Uses

type SyncPoolCompessors struct {
    GzipWriterPool *sync.Pool
    GzipReaderPool *sync.Pool
    ZlibWriterPool *sync.Pool
}

SyncPoolCompessors is a CompressorProvider that use the standard sync.Pool.

func NewSyncPoolCompessors Uses

func NewSyncPoolCompessors() *SyncPoolCompessors

NewSyncPoolCompessors returns a new ("empty") SyncPoolCompessors.

func (*SyncPoolCompessors) AcquireGzipReader Uses

func (s *SyncPoolCompessors) AcquireGzipReader() *gzip.Reader

func (*SyncPoolCompessors) AcquireGzipWriter Uses

func (s *SyncPoolCompessors) AcquireGzipWriter() *gzip.Writer

func (*SyncPoolCompessors) AcquireZlibWriter Uses

func (s *SyncPoolCompessors) AcquireZlibWriter() *zlib.Writer

func (*SyncPoolCompessors) ReleaseGzipReader Uses

func (s *SyncPoolCompessors) ReleaseGzipReader(r *gzip.Reader)

func (*SyncPoolCompessors) ReleaseGzipWriter Uses

func (s *SyncPoolCompessors) ReleaseGzipWriter(w *gzip.Writer)

func (*SyncPoolCompessors) ReleaseZlibWriter Uses

func (s *SyncPoolCompessors) ReleaseZlibWriter(w *zlib.Writer)

type TypeNameHandleFunction Uses

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 Uses

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 Uses

func RegisteredWebServices() []*WebService

RegisteredWebServices returns the collections of WebServices from the DefaultContainer

func (*WebService) ApiVersion Uses

func (w *WebService) ApiVersion(apiVersion string) *WebService

ApiVersion sets the API version for documentation purposes.

func (*WebService) BodyParameter Uses

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 Uses

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 Uses

func (w *WebService) DELETE(subPath string) *RouteBuilder

DELETE is a shortcut for .Method("DELETE").Path(subPath)

func (*WebService) Doc Uses

func (w *WebService) Doc(plainText string) *WebService

Doc is used to set the documentation of this service.

func (*WebService) Documentation Uses

func (w *WebService) Documentation() string

Documentation returns it.

func (*WebService) Filter Uses

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 Uses

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 Uses

func (w *WebService) GET(subPath string) *RouteBuilder

GET is a shortcut for .Method("GET").Path(subPath)

func (*WebService) HEAD Uses

func (w *WebService) HEAD(subPath string) *RouteBuilder

HEAD is a shortcut for .Method("HEAD").Path(subPath)

func (*WebService) HeaderParameter Uses

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 Uses

func (w *WebService) Method(httpMethod string) *RouteBuilder

Method creates a new RouteBuilder and initialize its http method

func (*WebService) PATCH Uses

func (w *WebService) PATCH(subPath string) *RouteBuilder

PATCH is a shortcut for .Method("PATCH").Path(subPath)

func (*WebService) POST Uses

func (w *WebService) POST(subPath string) *RouteBuilder

POST is a shortcut for .Method("POST").Path(subPath)

func (*WebService) PUT Uses

func (w *WebService) PUT(subPath string) *RouteBuilder

PUT is a shortcut for .Method("PUT").Path(subPath)

func (*WebService) Param Uses

func (w *WebService) Param(parameter *Parameter) *WebService

Param adds a PathParameter to document parameters used in the root path.

func (*WebService) Path Uses

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 Uses

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 Uses

func (w *WebService) PathParameters() []*Parameter

PathParameters return the path parameter names for (shared among its Routes)

func (*WebService) Produces Uses

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 Uses

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 Uses

func (w *WebService) RemoveRoute(path, method string) error

RemoveRoute removes the specified route, looks for something that matches 'path' and 'method'

func (*WebService) RootPath Uses

func (w *WebService) RootPath() string

RootPath returns the RootPath associated with this WebService. Default "/"

func (*WebService) Route Uses

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 Uses

func (w *WebService) Routes() []Route

Routes returns the Routes associated with this WebService

func (*WebService) SetDynamicRoutes Uses

func (w *WebService) SetDynamicRoutes(enable bool)

func (*WebService) TypeNameHandler Uses

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 Uses

func (w *WebService) Version() string

Version returns the API version for documentation purposes.

Directories

PathSynopsis
examples
examples/google_app_engine
examples/google_app_engine/datastore
examples/msgpack
log

Package restful imports 21 packages (graph) and is imported by 1295 packages. Updated 2019-09-11. Refresh now. Tools for package owners.