doc.go 7.3 KB

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