# 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
Usage
Without Go Modules
All versions up to v2.*.*
(on the master) are not supporting Go modules.
import (
restful "github.com/emicklei/go-restful"
)
Using Go Modules
As of version v3.0.0
(on the v3 branch), this package supports Go modules.
import (
restful "github.com/emicklei/go-restful/v3"
)
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")
...
}
Features
- Routes for request → function mapping with path parameter (e.g. {id} but also prefix_{var} and {var}_suffix) support
- Configurable router:
- (default) Fast routing algorithm that allows static elements, google custom method, regular expressions and dynamic parameters in the URL path (e.g. /resource/name:customVerb, /meetings/{id} or /static/{subpath:*})
- Routing algorithm after JSR311 that is implemented using (but does not accept) regular expressions
- Request API for reading structs from JSON/XML and accessing parameters (path,query,header)
- Response API for writing structs to JSON/XML and setting headers
- Customizable encoding using EntityReaderWriter registration
- 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 request and response payloads
- Automatic responses on OPTIONS (using a filter)
- Automatic CORS request handling (using a filter)
- API declaration for Swagger UI (go-restful-openapi)
- Panic recovery to produce HTTP 500, customizable using RecoverHandler(...)
- Route errors produce HTTP 404/405/406/415 errors, customizable using ServiceErrorHandler(...)
- Configurable (trace) logging
- Customizable gzip/deflate readers and writers using CompressorProvider registration
- Inject your own http.Handler using the
HttpMiddlewareHandlerToFilter
function
How to customize
There are several hooks to customize the behavior of the go-restful package.
- Router algorithm
- Panic recovery
- JSON decoder
- Trace logging
- Compression
- Encoders for other serializers
- Use the package variable
TrimRightSlashEnabled
(default true) to control the behavior of matching routes that end with a slash/
Resources
- Example programs
- Example posted on blog
- Design explained on blog
- sourcegraph
- showcase: Zazkia - tcp proxy for testing resiliency
- showcase: Mora - MongoDB REST Api server
Type git shortlog -s
for a full list of contributors.
© 2012 - 2023, http://ernestmicklei.com. MIT License. Contributions are welcome.
# Functions
Add registers a new WebService add it to the DefaultContainer.
BodyParameter creates a new Parameter of kind Body for documentation purposes.
CurrentCompressorProvider returns the current CompressorProvider.
If ContentType is missing or */* is given then fall back to this type, otherwise a "Unable to unmarshal content of type:" response is returned.
DefaultResponseContentType set a default.
EnableTracing can be used to Trace logging on and off.
Filter appends a container FilterFunction from the DefaultContainer.
FormParameter creates a new Parameter of kind Form (using application/x-www-form-urlencoded) for documentation purposes.
HeaderParameter creates a new Parameter of kind (Http) Header for documentation purposes.
HttpMiddlewareHandlerToFilter converts a HttpMiddlewareHandler to a FilterFunction.
NewBoundedCachedCompressors returns a new, with filled cache, BoundedCachedCompressors.
NewCompressingResponseWriter create a CompressingResponseWriter for a known encoding = {gzip,deflate}.
NewContainer creates a new Container using a new ServeMux and default router (CurlyRouter).
NewEntityAccessorJSON returns a new EntityReaderWriter for accessing JSON content.
NewEntityAccessorXML returns a new EntityReaderWriter for accessing XML content.
NewError returns a ServiceError using the code and reason.
NewErrorWithHeader returns a ServiceError using the code, reason and header.
NewResponse creates a new response based on a http ResponseWriter.
NewSyncPoolCompessors returns a new ("empty") SyncPoolCompessors.
NoBrowserCacheFilter is a filter function to set HTTP headers that disable browser caching See examples/restful-no-cache-filter.go for usage.
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.
PathParameter creates a new Parameter of kind Path for documentation purposes.
QueryParameter creates a new Parameter of kind Query for documentation purposes.
RegisteredWebServices returns the collections of WebServices from the DefaultContainer.
RegisterEntityAccessor add/overrides the ReaderWriter for encoding content with this MIME type.
SetCompressorProvider sets the actual provider of compressors (zlib or gzip).
SetLogger exposes the setter for the global logger on the top-level package.
TraceLogger enables detailed logging of Http request matching and filter invocation.
# Constants
BodyParameterKind = indicator of Request parameter type "body".
CollectionFormatCSV comma separated values `foo,bar`.
CollectionFormatMulti corresponds to multiple parameter instances instead of multiple values for a single instance `foo=bar&foo=baz`.
CollectionFormatPipes pipe separated values `foo|bar`.
CollectionFormatSSV space separated values `foo bar`.
CollectionFormatTSV tab separated values `foo\tbar`.
FormParameterKind = indicator of Request parameter type "form".
HeaderParameterKind = indicator of Request parameter type "header".
Accept or Content-Type used in Consumes() and/or Produces().
If Content-Type is not present in request, use the default.
Accept or Content-Type used in Consumes() and/or Produces().
Accept or Content-Type used in Consumes() and/or Produces().
MultiPartFormParameterKind = indicator of Request parameter type "multipart/form-data".
PathParameterKind = indicator of Request parameter type "path".
QueryParameterKind = indicator of Request parameter type "query".
# Variables
DefaultContainer is a restful.Container that uses http.DefaultServeMux.
DefaultResponseMimeType is DEPRECATED, use DefaultResponseContentType(mime).
If set the true then panics will not be caught to return HTTP 500.
OBSOLETE : use restful.DefaultContainer.EnableContentEncoding(true) to change this setting.
PrettyPrintResponses controls the indentation feature of XML and JSON serialization.
TrimRightSlashEnabled controls whether - path on route building is using path.Join - the path of the incoming request is trimmed of its slash suffux.
# Structs
BoundedCachedCompressors is a CompressorProvider that uses a cache with a fixed amount of writers and readers (resources).
CompressingResponseWriter is a http.ResponseWriter that can perform content encoding (gzip and zlib).
Container holds a collection of WebServices and a http.ServeMux to dispatch http requests.
CrossOriginResourceSharing is used to create a Container Filter that implements CORS.
CurlyRouter expects Routes with paths that contain zero or more parameters in curly brackets.
ExtensionProperties provides storage of vendor extensions for entities.
FilterChain is a request scoped object to process one or more filters before calling the target RouteFunction.
Header describes a header for a response of the API
For more information: http://goo.gl/8us55a#headerObject.
Items describe swagger simple schemas for headers.
Parameter is for documententing the parameter used in a Http Request ParameterData kinds are Path,Query and Body.
ParameterData represents the state of a Parameter.
Request is a wrapper for a http Request that provides convenience methods.
Response is a wrapper on the actual http ResponseWriter It provides several convenience methods to prepare and write response content.
ResponseError represents a response; not necessarily an error.
Route binds a HTTP Method,Path,Consumes combination to a RouteFunction.
RouteBuilder is a helper to construct Routes.
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.
ServiceError is a transport object to pass information about a non-Http error occurred in a WebService while processing a request.
SyncPoolCompessors is a CompressorProvider that use the standard sync.Pool.
WebService holds a collection of Route values that bind a Http Method + URL Path to a function.
# Interfaces
CompressorProvider describes a component that can provider compressors for the std methods.
EntityReaderWriter can read and write values using an encoding such as JSON,XML.
PathProcessor is extra behaviour that a Router can provide to extract path parameters from the path.
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 aliases
FilterFunction definitions must call ProcessFilter on the FilterChain to pass on the control and eventually call the RouteFunction.
HttpMiddlewareHandler is a function that takes a http.Handler and returns a http.Handler.
RecoverHandleFunction declares functions that can be used to handle a panic situation.
RouteFunction declares the signature of a function that can be bound to a Route.
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.
ServiceErrorHandleFunction declares functions that can be used to handle a service error situation.
TypeNameHandleFunction declares functions that can handle translating the name of a sample object into the restful documentation for the service.