2 Package restful , a lean package for creating REST-style WebServices without magic.
6 A WebService has a collection of Route objects that dispatch incoming Http Requests to a function calls.
7 Typically, a WebService has a root path (e.g. /users) and defines common MIME types for its routes.
8 WebServices must be added to a container (see below) in order to handler Http requests from a server.
10 A Route is defined by a HTTP method, an URL path and (optionally) the MIME types it consumes (Content-Type) and produces (Accept).
11 This package has the logic to find the best matching Route and if found, call its Function.
13 ws := new(restful.WebService)
16 Consumes(restful.MIME_JSON, restful.MIME_XML).
17 Produces(restful.MIME_JSON, restful.MIME_XML)
19 ws.Route(ws.GET("/{user-id}").To(u.findUser)) // u is a UserResource
23 // GET http://localhost:8080/users/1
24 func (u UserResource) findUser(request *restful.Request, response *restful.Response) {
25 id := request.PathParameter("user-id")
29 The (*Request, *Response) arguments provide functions for reading information from the request and writing information back to the response.
31 See the example https://github.com/emicklei/go-restful/blob/master/examples/restful-user-resource.go with a full implementation.
33 Regular expression matching Routes
35 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.
36 For example, /persons/{name:[A-Z][A-Z]} can be used to restrict values for the parameter "name" to only contain capital alphabetic characters.
37 Regular expressions must use the standard Go syntax as described in the regexp package. (https://code.google.com/p/re2/wiki/Syntax)
38 This feature requires the use of a CurlyRouter.
42 A Container holds a collection of WebServices, Filters and a http.ServeMux for multiplexing http requests.
43 Using the statements "restful.Add(...) and restful.Filter(...)" will register WebServices and Filters to the Default Container.
44 The Default container of go-restful uses the http.DefaultServeMux.
45 You can create your own Container and create a new http.Server for that particular container.
47 container := restful.NewContainer()
48 server := &http.Server{Addr: ":8081", Handler: container}
52 A filter dynamically intercepts requests and responses to transform or use the information contained in the requests or responses.
53 You can use filters to perform generic logging, measurement, authentication, redirect, set response headers etc.
54 In the restful package there are three hooks into the request,response flow where filters can be added.
55 Each filter must define a FilterFunction:
57 func (req *restful.Request, resp *restful.Response, chain *restful.FilterChain)
59 Use the following statement to pass the request,response pair to the next filter or RouteFunction
61 chain.ProcessFilter(req, resp)
65 These are processed before any registered WebService.
67 // install a (global) filter for the default container (processed before any webservice)
68 restful.Filter(globalLogging)
72 These are processed before any Route of a WebService.
74 // install a webservice filter (processed before any route)
75 ws.Filter(webserviceLogging).Filter(measureTime)
80 These are processed before calling the function associated with the Route.
82 // install 2 chained route filters (processed before calling findUser)
83 ws.Route(ws.GET("/{user-id}").Filter(routeLogging).Filter(NewCountFilter().routeCounter).To(findUser))
85 See the example https://github.com/emicklei/go-restful/blob/master/examples/restful-filters.go with full implementations.
89 Two encodings are supported: gzip and deflate. To enable this for all responses:
91 restful.DefaultContainer.EnableContentEncoding(true)
93 If a Http request includes the Accept-Encoding header then the response content will be compressed using the specified encoding.
94 Alternatively, you can create a Filter that performs the encoding and install it per WebService or Route.
96 See the example https://github.com/emicklei/go-restful/blob/master/examples/restful-encoding-filter.go
100 By installing a pre-defined container filter, your Webservice(s) can respond to the OPTIONS Http request.
102 Filter(OPTIONSFilter())
106 By installing the filter of a CrossOriginResourceSharing (CORS), your WebService(s) can handle CORS requests.
108 cors := CrossOriginResourceSharing{ExposeHeaders: []string{"X-My-Header"}, CookiesAllowed: false, Container: DefaultContainer}
113 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.
114 For this reason HTTP status codes exist and it is important to use the correct code in every exceptional situation.
118 If path or query parameters are not valid (content or type) then use http.StatusBadRequest.
122 Despite a valid URI, the resource requested may not be available
124 500: Internal Server Error
126 If the application logic could not process the request (or write the response) then use http.StatusInternalServerError.
128 405: Method Not Allowed
130 The request has a valid URL but the method (GET,PUT,POST,...) is not allowed.
134 The request does not have or has an unknown Accept Header set for this operation.
136 415: Unsupported Media Type
138 The request does not have or has an unknown Content-Type Header set for this operation.
142 In addition to setting the correct (error) Http status code, you can choose to write a ServiceError message on the response.
146 This package has several options that affect the performance of your service. It is important to understand them and how you can change it.
148 restful.DefaultContainer.DoNotRecover(false)
150 DoNotRecover controls whether panics will be caught to return HTTP 500.
151 If set to false, the container will recover from panics.
152 Default value is true
154 restful.SetCompressorProvider(NewBoundedCachedCompressors(20, 20))
156 If content encoding is enabled then the default strategy for getting new gzip/zlib writers and readers is to use a sync.Pool.
157 Because writers are expensive structures, performance is even more improved when using a preloaded cache. You can also inject your own implementation.
161 This package has the means to produce detail logging of the complete Http request matching process and filter invocation.
162 Enabling this feature requires you to set an implementation of restful.StdLogger (e.g. log.Logger) instance such as:
164 restful.TraceLogger(log.New(os.Stdout, "[restful] ", log.LstdFlags|log.Lshortfile))
168 The restful.SetLogger() method allows you to override the logger used by the package. By default restful
169 uses the standard library `log` package and logs to stdout. Different logging packages are supported as
170 long as they conform to `StdLogger` interface defined in the `log` sub-package, writing an adapter for your
171 preferred package is simple.
175 [project]: https://github.com/emicklei/go-restful
177 [examples]: https://github.com/emicklei/go-restful/blob/master/examples
179 [design]: http://ernestmicklei.com/2012/11/11/go-restful-api-design/
181 [showcases]: https://github.com/emicklei/mora, https://github.com/emicklei/landskape
183 (c) 2012-2015, http://ernestmicklei.com. MIT License