restful

package module
v1.1.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 6, 2015 License: MIT Imports: 17 Imported by: 0

README

go-restful

package for building REST-style Web Services using Google Go

REST asks developers to use HTTP methods explicitly and in a way that's consistent with the protocol definition. This basic REST design principle establishes a one-to-one mapping between create, read, update, and delete (CRUD) operations and HTTP methods. According to this mapping:

  • GET = Retrieve a representation of a resource
  • POST = Create if you are sending content to the server to create a subordinate of the specified resource collection, using some server-side algorithm.
  • PUT = Create if you are sending the full content of the specified resource (URI).
  • PUT = Update if you are updating the full content of the specified resource.
  • DELETE = Delete if you are requesting the server to delete the resource
  • PATCH = Update partial content of a resource
  • OPTIONS = Get information about the communication options for the request URI
Example
ws := new(restful.WebService)
ws.
	Path("/users").
	Consumes(restful.MIME_XML, restful.MIME_JSON).
	Produces(restful.MIME_JSON, restful.MIME_XML)

ws.Route(ws.GET("/{user-id}").To(u.findUser).
	Doc("get a user").
	Param(ws.PathParameter("user-id", "identifier of the user").DataType("string")).
	Writes(User{}))		
...
	
func (u UserResource) findUser(request *restful.Request, response *restful.Response) {
	id := request.PathParameter("user-id")
	...
}

Full API of a UserResource

Features
  • Routes for request → function mapping with path parameter (e.g. {id}) support
  • Configurable router:
    • Routing algorithm after JSR311 that is implemented using (but doest not accept) regular expressions (See RouterJSR311 which is used by default)
    • Fast routing algorithm that allows static elements, regular expressions and dynamic parameters in the URL path (e.g. /meetings/{id} or /static/{subpath:*}, See CurlyRouter)
  • Request API for reading structs from JSON/XML and accesing parameters (path,query,header)
  • Response API for writing structs to JSON/XML and setting headers
  • Filters for intercepting the request → response flow on Service or Route level
  • Request-scoped variables using attributes
  • Containers for WebServices on different HTTP endpoints
  • Content encoding (gzip,deflate) of responses
  • Automatic responses on OPTIONS (using a filter)
  • Automatic CORS request handling (using a filter)
  • API declaration for Swagger UI (see swagger package)
  • Panic recovery to produce HTTP 500, customizable using RecoverHandler(...)
Resources

Build Statuslibrary users authors xrefs

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

Type git shortlog -s for a full list of contributors.

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.Router(CurlyRouter{})

The default router is the RouterJSR311 which is an implementation of its spec (http://jsr311.java.net/nonav/releases/1.1/spec/spec.html). However, it uses regular expressions for all its routes which, depending on your usecase, may consume a significant amount of time. The CurlyRouter implementation is more lightweight that also allows you to use wildcards and expressions, but only if needed.

restful.DefaultContainer.DoNotRecover(true)

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 false; it will recover from panics. This has performance implications.

restful.SetCacheReadEntity(false)

SetCacheReadEntity controls whether the response data ([]byte) is cached such that ReadEntity is repeatable. If you expect to read large amounts of payload data, and you do not use this feature, you should set it to false.

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 a log.Logger instance such as:

restful.TraceLogger(log.New(os.Stdout, "[restful] ", log.LstdFlags|log.Lshortfile))

Resources

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

Index

Examples

Constants

View Source
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()

	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"
)
View Source
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
)

Variables

View Source
var DefaultResponseMimeType string

DEPRECATED, use DefaultResponseContentType(mime)

View Source
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)

View Source
var EnableContentEncoding = false

OBSOLETE : use restful.DefaultContainer.EnableContentEncoding(true) to change this setting.

View Source
var PrettyPrintResponses = true

PrettyPrintResponses controls the indentation feature of XML and JSON serialization in the response methods WriteEntity, WriteAsJson, and WriteAsXml.

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)

If Accept header matching fails, fall back to this type, otherwise a "406: Not Acceptable" response is returned. Valid values are restful.MIME_JSON and restful.MIME_XML Example:

restful.DefaultResponseContentType(restful.MIME_JSON)

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 SetCacheReadEntity added in v1.1.2

func SetCacheReadEntity(doCache bool)

SetCacheReadEntity controls whether the response data ([]byte) is cached such that ReadEntity is repeatable. Default is true (due to backwardcompatibility). For better performance, you should set it to false if you don't need it.

func TraceLogger added in v1.1.3

func TraceLogger(logger *log.Logger)

TraceLogger enables detailed logging of Http request matching and filter invocation. Default no logger is set.

Types

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

Close the underlying compressor

func (*CompressingResponseWriter) CloseNotify

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

CloseNotify is part of http.CloseNotifier interface

func (*CompressingResponseWriter) Header

Header is part of http.ResponseWriter interface

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 Container

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

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

func (*Container) Add

func (c *Container) Add(service *WebService) *Container

Add a WebService to the Container. It will detect duplicate root paths and panic in that case.

func (*Container) DoNotRecover

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 false = recover from panics. This has performance implications.

func (*Container) EnableContentEncoding

func (c *Container) EnableContentEncoding(enabled bool)

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

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 added in v1.1.3

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

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

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

func (c *Container) Router(aRouter RouteSelector)

Router changes the default Router (currently RouterJSR311)

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

type CrossOriginResourceSharing

type CrossOriginResourceSharing struct {
	ExposeHeaders  []string // list of Header names
	AllowedHeaders []string // list of Header names
	AllowedDomains []string // list of allowed values for Http Origin. If empty all are allowed.
	AllowedMethods []string
	MaxAge         int // number of seconds before requiring new Options request
	CookiesAllowed bool
	Container      *Container
}

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

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

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

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

AllowMultiple sets the allowMultiple field and return the receiver

func (*Parameter) AllowableValues

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

AllowableValues sets the allowableValues field and return the receiver

func (*Parameter) Data

func (p *Parameter) Data() ParameterData

Data returns the state of the Parameter

func (*Parameter) DataType

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

DataType sets the dataType field and return the receiver

func (*Parameter) Kind

func (p *Parameter) Kind() int

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

func (*Parameter) Required

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

Required sets the required field and return the receiver

type ParameterData

type ParameterData struct {
	Name, Description, DataType string
	Kind                        int
	Required                    bool
	AllowableValues             map[string]string
	AllowMultiple               bool
}

ParameterData represents the state of a Parameter. It is made public to make it accessible to e.g. the Swagger package.

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

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 added in v1.1.0

func NewRequest(httpRequest *http.Request) *Request

func (Request) Attribute

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

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

func (*Request) BodyParameter

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

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

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

func (*Request) PathParameter

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

PathParameter accesses the Path parameter value by its name

func (*Request) PathParameters

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

PathParameters accesses the Path parameter values

func (*Request) QueryParameter

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

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

func (*Request) ReadEntity

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

ReadEntity checks the Accept header and reads the content into the entityPointer May be called multiple times in the request-response flow

func (Request) SelectedRoutePath

func (r Request) SelectedRoutePath() string

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

func (*Request) SetAttribute

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

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

Creates a new response based on a http ResponseWriter.

func (Response) AddHeader

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

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

func (Response) CloseNotify

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

CloseNotify is part of http.CloseNotifier interface

func (Response) ContentLength

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

func (r Response) InternalServerError() Response

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

func (*Response) PrettyPrint added in v1.1.3

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 added in v1.1.3

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

func (r Response) StatusCode() int

StatusCode returns the code that has been written using WriteHeader.

func (*Response) Write

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

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

WriteAsJson is a convenience method for writing a value in json

func (*Response) WriteAsXml

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

WriteAsXml is a convenience method for writing a value in xml (requires Xml tags on the value)

func (*Response) WriteEntity

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

WriteEntity marshals the value using the representation denoted by the Accept Header (XML or JSON) If no Accept header is specified (or */*) then return the Content-Type as specified by the first in the Route.Produces. If an Accept header is specified then return 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 nothing is written. You may want to call WriteHeader(http.StatusNotFound) instead. Current implementation ignores any q-parameters in the Accept Header.

func (*Response) WriteError

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

WriteError write the http status and the error string on the response.

func (*Response) WriteErrorString

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

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

func (*Response) WriteHeader

func (r *Response) WriteHeader(httpStatus int)

WriteHeader is overridden to remember the Status Code that has been written. Note that using this method, the status value is only written when

  • calling WriteEntity,
  • or directly calling WriteAsXml or WriteAsJson,
  • or if the status is one for which no response is allowed (i.e., 204 (http.StatusNoContent) or 304 (http.StatusNotModified))

func (*Response) WriteServiceError

func (r *Response) WriteServiceError(httpStatus int, err ServiceError) error

WriteServiceError is a convenience method for a responding with a ServiceError and a status

type ResponseError added in v1.1.3

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

type Route

type Route struct {
	Method   string
	Produces []string
	Consumes []string
	Path     string // webservice root path + described path
	Function RouteFunction
	Filters  []FilterFunction

	// documentation
	Doc                     string
	Notes                   string
	Operation               string
	ParameterDocs           []*Parameter
	ResponseErrors          map[int]ResponseError
	ReadSample, WriteSample interface{} // structs that model an example request or response payload
	// contains filtered or unexported fields
}

Route binds a HTTP Method,Path,Consumes combination to a RouteFunction.

func (Route) String

func (r Route) String() string

for debugging

type RouteBuilder

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

RouteBuilder is a helper to construct Routes.

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

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 acutal method/function call is of the Route.

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{}) *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) 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

type RouteFunction func(*Request, *Response)

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

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

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

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.

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 (ServiceError) Error

func (s ServiceError) Error() string

Error returns a text representation of the service error

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) 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 amoung 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) 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) Version added in v1.1.3

func (w WebService) Version() string

Version returns the API version for documentation purposes.

Directories

Path Synopsis
Package swagger implements the structures of the Swagger https://github.com/wordnik/swagger-spec/blob/master/versions/1.2.md
Package swagger implements the structures of the Swagger https://github.com/wordnik/swagger-spec/blob/master/versions/1.2.md

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL