web_service.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. package restful
  2. import (
  3. "errors"
  4. "os"
  5. "reflect"
  6. "sync"
  7. "github.com/emicklei/go-restful/log"
  8. )
  9. // Copyright 2013 Ernest Micklei. All rights reserved.
  10. // Use of this source code is governed by a license
  11. // that can be found in the LICENSE file.
  12. // WebService holds a collection of Route values that bind a Http Method + URL Path to a function.
  13. type WebService struct {
  14. rootPath string
  15. pathExpr *pathExpression // cached compilation of rootPath as RegExp
  16. routes []Route
  17. produces []string
  18. consumes []string
  19. pathParameters []*Parameter
  20. filters []FilterFunction
  21. documentation string
  22. apiVersion string
  23. typeNameHandleFunc TypeNameHandleFunction
  24. dynamicRoutes bool
  25. // protects 'routes' if dynamic routes are enabled
  26. routesLock sync.RWMutex
  27. }
  28. func (w *WebService) SetDynamicRoutes(enable bool) {
  29. w.dynamicRoutes = enable
  30. }
  31. // TypeNameHandleFunction declares functions that can handle translating the name of a sample object
  32. // into the restful documentation for the service.
  33. type TypeNameHandleFunction func(sample interface{}) string
  34. // TypeNameHandler sets the function that will convert types to strings in the parameter
  35. // and model definitions. If not set, the web service will invoke
  36. // reflect.TypeOf(object).String().
  37. func (w *WebService) TypeNameHandler(handler TypeNameHandleFunction) *WebService {
  38. w.typeNameHandleFunc = handler
  39. return w
  40. }
  41. // reflectTypeName is the default TypeNameHandleFunction and for a given object
  42. // returns the name that Go identifies it with (e.g. "string" or "v1.Object") via
  43. // the reflection API.
  44. func reflectTypeName(sample interface{}) string {
  45. return reflect.TypeOf(sample).String()
  46. }
  47. // compilePathExpression ensures that the path is compiled into a RegEx for those routers that need it.
  48. func (w *WebService) compilePathExpression() {
  49. compiled, err := newPathExpression(w.rootPath)
  50. if err != nil {
  51. log.Printf("[restful] invalid path:%s because:%v", w.rootPath, err)
  52. os.Exit(1)
  53. }
  54. w.pathExpr = compiled
  55. }
  56. // ApiVersion sets the API version for documentation purposes.
  57. func (w *WebService) ApiVersion(apiVersion string) *WebService {
  58. w.apiVersion = apiVersion
  59. return w
  60. }
  61. // Version returns the API version for documentation purposes.
  62. func (w *WebService) Version() string { return w.apiVersion }
  63. // Path specifies the root URL template path of the WebService.
  64. // All Routes will be relative to this path.
  65. func (w *WebService) Path(root string) *WebService {
  66. w.rootPath = root
  67. if len(w.rootPath) == 0 {
  68. w.rootPath = "/"
  69. }
  70. w.compilePathExpression()
  71. return w
  72. }
  73. // Param adds a PathParameter to document parameters used in the root path.
  74. func (w *WebService) Param(parameter *Parameter) *WebService {
  75. if w.pathParameters == nil {
  76. w.pathParameters = []*Parameter{}
  77. }
  78. w.pathParameters = append(w.pathParameters, parameter)
  79. return w
  80. }
  81. // PathParameter creates a new Parameter of kind Path for documentation purposes.
  82. // It is initialized as required with string as its DataType.
  83. func (w *WebService) PathParameter(name, description string) *Parameter {
  84. return PathParameter(name, description)
  85. }
  86. // PathParameter creates a new Parameter of kind Path for documentation purposes.
  87. // It is initialized as required with string as its DataType.
  88. func PathParameter(name, description string) *Parameter {
  89. p := &Parameter{&ParameterData{Name: name, Description: description, Required: true, DataType: "string"}}
  90. p.bePath()
  91. return p
  92. }
  93. // QueryParameter creates a new Parameter of kind Query for documentation purposes.
  94. // It is initialized as not required with string as its DataType.
  95. func (w *WebService) QueryParameter(name, description string) *Parameter {
  96. return QueryParameter(name, description)
  97. }
  98. // QueryParameter creates a new Parameter of kind Query for documentation purposes.
  99. // It is initialized as not required with string as its DataType.
  100. func QueryParameter(name, description string) *Parameter {
  101. p := &Parameter{&ParameterData{Name: name, Description: description, Required: false, DataType: "string"}}
  102. p.beQuery()
  103. return p
  104. }
  105. // BodyParameter creates a new Parameter of kind Body for documentation purposes.
  106. // It is initialized as required without a DataType.
  107. func (w *WebService) BodyParameter(name, description string) *Parameter {
  108. return BodyParameter(name, description)
  109. }
  110. // BodyParameter creates a new Parameter of kind Body for documentation purposes.
  111. // It is initialized as required without a DataType.
  112. func BodyParameter(name, description string) *Parameter {
  113. p := &Parameter{&ParameterData{Name: name, Description: description, Required: true}}
  114. p.beBody()
  115. return p
  116. }
  117. // HeaderParameter creates a new Parameter of kind (Http) Header for documentation purposes.
  118. // It is initialized as not required with string as its DataType.
  119. func (w *WebService) HeaderParameter(name, description string) *Parameter {
  120. return HeaderParameter(name, description)
  121. }
  122. // HeaderParameter creates a new Parameter of kind (Http) Header for documentation purposes.
  123. // It is initialized as not required with string as its DataType.
  124. func HeaderParameter(name, description string) *Parameter {
  125. p := &Parameter{&ParameterData{Name: name, Description: description, Required: false, DataType: "string"}}
  126. p.beHeader()
  127. return p
  128. }
  129. // FormParameter creates a new Parameter of kind Form (using application/x-www-form-urlencoded) for documentation purposes.
  130. // It is initialized as required with string as its DataType.
  131. func (w *WebService) FormParameter(name, description string) *Parameter {
  132. return FormParameter(name, description)
  133. }
  134. // FormParameter creates a new Parameter of kind Form (using application/x-www-form-urlencoded) for documentation purposes.
  135. // It is initialized as required with string as its DataType.
  136. func FormParameter(name, description string) *Parameter {
  137. p := &Parameter{&ParameterData{Name: name, Description: description, Required: false, DataType: "string"}}
  138. p.beForm()
  139. return p
  140. }
  141. // Route creates a new Route using the RouteBuilder and add to the ordered list of Routes.
  142. func (w *WebService) Route(builder *RouteBuilder) *WebService {
  143. w.routesLock.Lock()
  144. defer w.routesLock.Unlock()
  145. builder.copyDefaults(w.produces, w.consumes)
  146. w.routes = append(w.routes, builder.Build())
  147. return w
  148. }
  149. // RemoveRoute removes the specified route, looks for something that matches 'path' and 'method'
  150. func (w *WebService) RemoveRoute(path, method string) error {
  151. if !w.dynamicRoutes {
  152. return errors.New("dynamic routes are not enabled.")
  153. }
  154. w.routesLock.Lock()
  155. defer w.routesLock.Unlock()
  156. newRoutes := make([]Route, (len(w.routes) - 1))
  157. current := 0
  158. for ix := range w.routes {
  159. if w.routes[ix].Method == method && w.routes[ix].Path == path {
  160. continue
  161. }
  162. newRoutes[current] = w.routes[ix]
  163. current = current + 1
  164. }
  165. w.routes = newRoutes
  166. return nil
  167. }
  168. // Method creates a new RouteBuilder and initialize its http method
  169. func (w *WebService) Method(httpMethod string) *RouteBuilder {
  170. return new(RouteBuilder).typeNameHandler(w.typeNameHandleFunc).servicePath(w.rootPath).Method(httpMethod)
  171. }
  172. // Produces specifies that this WebService can produce one or more MIME types.
  173. // Http requests must have one of these values set for the Accept header.
  174. func (w *WebService) Produces(contentTypes ...string) *WebService {
  175. w.produces = contentTypes
  176. return w
  177. }
  178. // Consumes specifies that this WebService can consume one or more MIME types.
  179. // Http requests must have one of these values set for the Content-Type header.
  180. func (w *WebService) Consumes(accepts ...string) *WebService {
  181. w.consumes = accepts
  182. return w
  183. }
  184. // Routes returns the Routes associated with this WebService
  185. func (w *WebService) Routes() []Route {
  186. if !w.dynamicRoutes {
  187. return w.routes
  188. }
  189. // Make a copy of the array to prevent concurrency problems
  190. w.routesLock.RLock()
  191. defer w.routesLock.RUnlock()
  192. result := make([]Route, len(w.routes))
  193. for ix := range w.routes {
  194. result[ix] = w.routes[ix]
  195. }
  196. return result
  197. }
  198. // RootPath returns the RootPath associated with this WebService. Default "/"
  199. func (w *WebService) RootPath() string {
  200. return w.rootPath
  201. }
  202. // PathParameters return the path parameter names for (shared amoung its Routes)
  203. func (w *WebService) PathParameters() []*Parameter {
  204. return w.pathParameters
  205. }
  206. // Filter adds a filter function to the chain of filters applicable to all its Routes
  207. func (w *WebService) Filter(filter FilterFunction) *WebService {
  208. w.filters = append(w.filters, filter)
  209. return w
  210. }
  211. // Doc is used to set the documentation of this service.
  212. func (w *WebService) Doc(plainText string) *WebService {
  213. w.documentation = plainText
  214. return w
  215. }
  216. // Documentation returns it.
  217. func (w *WebService) Documentation() string {
  218. return w.documentation
  219. }
  220. /*
  221. Convenience methods
  222. */
  223. // HEAD is a shortcut for .Method("HEAD").Path(subPath)
  224. func (w *WebService) HEAD(subPath string) *RouteBuilder {
  225. return new(RouteBuilder).typeNameHandler(w.typeNameHandleFunc).servicePath(w.rootPath).Method("HEAD").Path(subPath)
  226. }
  227. // GET is a shortcut for .Method("GET").Path(subPath)
  228. func (w *WebService) GET(subPath string) *RouteBuilder {
  229. return new(RouteBuilder).typeNameHandler(w.typeNameHandleFunc).servicePath(w.rootPath).Method("GET").Path(subPath)
  230. }
  231. // POST is a shortcut for .Method("POST").Path(subPath)
  232. func (w *WebService) POST(subPath string) *RouteBuilder {
  233. return new(RouteBuilder).typeNameHandler(w.typeNameHandleFunc).servicePath(w.rootPath).Method("POST").Path(subPath)
  234. }
  235. // PUT is a shortcut for .Method("PUT").Path(subPath)
  236. func (w *WebService) PUT(subPath string) *RouteBuilder {
  237. return new(RouteBuilder).typeNameHandler(w.typeNameHandleFunc).servicePath(w.rootPath).Method("PUT").Path(subPath)
  238. }
  239. // PATCH is a shortcut for .Method("PATCH").Path(subPath)
  240. func (w *WebService) PATCH(subPath string) *RouteBuilder {
  241. return new(RouteBuilder).typeNameHandler(w.typeNameHandleFunc).servicePath(w.rootPath).Method("PATCH").Path(subPath)
  242. }
  243. // DELETE is a shortcut for .Method("DELETE").Path(subPath)
  244. func (w *WebService) DELETE(subPath string) *RouteBuilder {
  245. return new(RouteBuilder).typeNameHandler(w.typeNameHandleFunc).servicePath(w.rootPath).Method("DELETE").Path(subPath)
  246. }