route_builder.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. package restful
  2. // Copyright 2013 Ernest Micklei. All rights reserved.
  3. // Use of this source code is governed by a license
  4. // that can be found in the LICENSE file.
  5. import (
  6. "fmt"
  7. "os"
  8. "reflect"
  9. "runtime"
  10. "strings"
  11. "sync/atomic"
  12. "github.com/emicklei/go-restful/v3/log"
  13. )
  14. // RouteBuilder is a helper to construct Routes.
  15. type RouteBuilder struct {
  16. rootPath string
  17. currentPath string
  18. produces []string
  19. consumes []string
  20. httpMethod string // required
  21. function RouteFunction // required
  22. filters []FilterFunction
  23. conditions []RouteSelectionConditionFunction
  24. allowedMethodsWithoutContentType []string // see Route
  25. typeNameHandleFunc TypeNameHandleFunction // required
  26. // documentation
  27. doc string
  28. notes string
  29. operation string
  30. readSample, writeSample interface{}
  31. parameters []*Parameter
  32. errorMap map[int]ResponseError
  33. defaultResponse *ResponseError
  34. metadata map[string]interface{}
  35. extensions map[string]interface{}
  36. deprecated bool
  37. contentEncodingEnabled *bool
  38. }
  39. // Do evaluates each argument with the RouteBuilder itself.
  40. // This allows you to follow DRY principles without breaking the fluent programming style.
  41. // Example:
  42. // ws.Route(ws.DELETE("/{name}").To(t.deletePerson).Do(Returns200, Returns500))
  43. //
  44. // func Returns500(b *RouteBuilder) {
  45. // b.Returns(500, "Internal Server Error", restful.ServiceError{})
  46. // }
  47. func (b *RouteBuilder) Do(oneArgBlocks ...func(*RouteBuilder)) *RouteBuilder {
  48. for _, each := range oneArgBlocks {
  49. each(b)
  50. }
  51. return b
  52. }
  53. // To bind the route to a function.
  54. // If this route is matched with the incoming Http Request then call this function with the *Request,*Response pair. Required.
  55. func (b *RouteBuilder) To(function RouteFunction) *RouteBuilder {
  56. b.function = function
  57. return b
  58. }
  59. // Method specifies what HTTP method to match. Required.
  60. func (b *RouteBuilder) Method(method string) *RouteBuilder {
  61. b.httpMethod = method
  62. return b
  63. }
  64. // Produces specifies what MIME types can be produced ; the matched one will appear in the Content-Type Http header.
  65. func (b *RouteBuilder) Produces(mimeTypes ...string) *RouteBuilder {
  66. b.produces = mimeTypes
  67. return b
  68. }
  69. // Consumes specifies what MIME types can be consumes ; the Accept Http header must matched any of these
  70. func (b *RouteBuilder) Consumes(mimeTypes ...string) *RouteBuilder {
  71. b.consumes = mimeTypes
  72. return b
  73. }
  74. // Path specifies the relative (w.r.t WebService root path) URL path to match. Default is "/".
  75. func (b *RouteBuilder) Path(subPath string) *RouteBuilder {
  76. b.currentPath = subPath
  77. return b
  78. }
  79. // Doc tells what this route is all about. Optional.
  80. func (b *RouteBuilder) Doc(documentation string) *RouteBuilder {
  81. b.doc = documentation
  82. return b
  83. }
  84. // Notes is a verbose explanation of the operation behavior. Optional.
  85. func (b *RouteBuilder) Notes(notes string) *RouteBuilder {
  86. b.notes = notes
  87. return b
  88. }
  89. // Reads tells what resource type will be read from the request payload. Optional.
  90. // 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.
  91. func (b *RouteBuilder) Reads(sample interface{}, optionalDescription ...string) *RouteBuilder {
  92. fn := b.typeNameHandleFunc
  93. if fn == nil {
  94. fn = reflectTypeName
  95. }
  96. typeAsName := fn(sample)
  97. description := ""
  98. if len(optionalDescription) > 0 {
  99. description = optionalDescription[0]
  100. }
  101. b.readSample = sample
  102. bodyParameter := &Parameter{&ParameterData{Name: "body", Description: description}}
  103. bodyParameter.beBody()
  104. bodyParameter.Required(true)
  105. bodyParameter.DataType(typeAsName)
  106. b.Param(bodyParameter)
  107. return b
  108. }
  109. // ParameterNamed returns a Parameter already known to the RouteBuilder. Returns nil if not.
  110. // Use this to modify or extend information for the Parameter (through its Data()).
  111. func (b RouteBuilder) ParameterNamed(name string) (p *Parameter) {
  112. for _, each := range b.parameters {
  113. if each.Data().Name == name {
  114. return each
  115. }
  116. }
  117. return p
  118. }
  119. // Writes tells what resource type will be written as the response payload. Optional.
  120. func (b *RouteBuilder) Writes(sample interface{}) *RouteBuilder {
  121. b.writeSample = sample
  122. return b
  123. }
  124. // Param allows you to document the parameters of the Route. It adds a new Parameter (does not check for duplicates).
  125. func (b *RouteBuilder) Param(parameter *Parameter) *RouteBuilder {
  126. if b.parameters == nil {
  127. b.parameters = []*Parameter{}
  128. }
  129. b.parameters = append(b.parameters, parameter)
  130. return b
  131. }
  132. // Operation allows you to document what the actual method/function call is of the Route.
  133. // Unless called, the operation name is derived from the RouteFunction set using To(..).
  134. func (b *RouteBuilder) Operation(name string) *RouteBuilder {
  135. b.operation = name
  136. return b
  137. }
  138. // ReturnsError is deprecated, use Returns instead.
  139. func (b *RouteBuilder) ReturnsError(code int, message string, model interface{}) *RouteBuilder {
  140. log.Print("ReturnsError is deprecated, use Returns instead.")
  141. return b.Returns(code, message, model)
  142. }
  143. // Returns allows you to document what responses (errors or regular) can be expected.
  144. // The model parameter is optional ; either pass a struct instance or use nil if not applicable.
  145. func (b *RouteBuilder) Returns(code int, message string, model interface{}) *RouteBuilder {
  146. err := ResponseError{
  147. Code: code,
  148. Message: message,
  149. Model: model,
  150. IsDefault: false, // this field is deprecated, use default response instead.
  151. }
  152. // lazy init because there is no NewRouteBuilder (yet)
  153. if b.errorMap == nil {
  154. b.errorMap = map[int]ResponseError{}
  155. }
  156. b.errorMap[code] = err
  157. return b
  158. }
  159. // ReturnsWithHeaders is similar to Returns, but can specify response headers
  160. func (b *RouteBuilder) ReturnsWithHeaders(code int, message string, model interface{}, headers map[string]Header) *RouteBuilder {
  161. b.Returns(code, message, model)
  162. err := b.errorMap[code]
  163. err.Headers = headers
  164. b.errorMap[code] = err
  165. return b
  166. }
  167. // DefaultReturns is a special Returns call that sets the default of the response.
  168. func (b *RouteBuilder) DefaultReturns(message string, model interface{}) *RouteBuilder {
  169. b.defaultResponse = &ResponseError{
  170. Message: message,
  171. Model: model,
  172. }
  173. return b
  174. }
  175. // Metadata adds or updates a key=value pair to the metadata map.
  176. func (b *RouteBuilder) Metadata(key string, value interface{}) *RouteBuilder {
  177. if b.metadata == nil {
  178. b.metadata = map[string]interface{}{}
  179. }
  180. b.metadata[key] = value
  181. return b
  182. }
  183. // AddExtension adds or updates a key=value pair to the extensions map.
  184. func (b *RouteBuilder) AddExtension(key string, value interface{}) *RouteBuilder {
  185. if b.extensions == nil {
  186. b.extensions = map[string]interface{}{}
  187. }
  188. b.extensions[key] = value
  189. return b
  190. }
  191. // Deprecate sets the value of deprecated to true. Deprecated routes have a special UI treatment to warn against use
  192. func (b *RouteBuilder) Deprecate() *RouteBuilder {
  193. b.deprecated = true
  194. return b
  195. }
  196. // AllowedMethodsWithoutContentType overrides the default list GET,HEAD,OPTIONS,DELETE,TRACE
  197. // If a request does not include a content-type header then
  198. // depending on the method, it may return a 415 Unsupported Media.
  199. // Must have uppercase HTTP Method names such as GET,HEAD,OPTIONS,...
  200. func (b *RouteBuilder) AllowedMethodsWithoutContentType(methods []string) *RouteBuilder {
  201. b.allowedMethodsWithoutContentType = methods
  202. return b
  203. }
  204. // ResponseError represents a response; not necessarily an error.
  205. type ResponseError struct {
  206. ExtensionProperties
  207. Code int
  208. Message string
  209. Model interface{}
  210. Headers map[string]Header
  211. IsDefault bool
  212. }
  213. // Header describes a header for a response of the API
  214. //
  215. // For more information: http://goo.gl/8us55a#headerObject
  216. type Header struct {
  217. *Items
  218. Description string
  219. }
  220. // Items describe swagger simple schemas for headers
  221. type Items struct {
  222. Type string
  223. Format string
  224. Items *Items
  225. CollectionFormat string
  226. Default interface{}
  227. }
  228. func (b *RouteBuilder) servicePath(path string) *RouteBuilder {
  229. b.rootPath = path
  230. return b
  231. }
  232. // Filter appends a FilterFunction to the end of filters for this Route to build.
  233. func (b *RouteBuilder) Filter(filter FilterFunction) *RouteBuilder {
  234. b.filters = append(b.filters, filter)
  235. return b
  236. }
  237. // If sets a condition function that controls matching the Route based on custom logic.
  238. // The condition function is provided the HTTP request and should return true if the route
  239. // should be considered.
  240. //
  241. // Efficiency note: the condition function is called before checking the method, produces, and
  242. // consumes criteria, so that the correct HTTP status code can be returned.
  243. //
  244. // Lifecycle note: no filter functions have been called prior to calling the condition function,
  245. // so the condition function should not depend on any context that might be set up by container
  246. // or route filters.
  247. func (b *RouteBuilder) If(condition RouteSelectionConditionFunction) *RouteBuilder {
  248. b.conditions = append(b.conditions, condition)
  249. return b
  250. }
  251. // ContentEncodingEnabled allows you to override the Containers value for auto-compressing this route response.
  252. func (b *RouteBuilder) ContentEncodingEnabled(enabled bool) *RouteBuilder {
  253. b.contentEncodingEnabled = &enabled
  254. return b
  255. }
  256. // If no specific Route path then set to rootPath
  257. // If no specific Produces then set to rootProduces
  258. // If no specific Consumes then set to rootConsumes
  259. func (b *RouteBuilder) copyDefaults(rootProduces, rootConsumes []string) {
  260. if len(b.produces) == 0 {
  261. b.produces = rootProduces
  262. }
  263. if len(b.consumes) == 0 {
  264. b.consumes = rootConsumes
  265. }
  266. }
  267. // typeNameHandler sets the function that will convert types to strings in the parameter
  268. // and model definitions.
  269. func (b *RouteBuilder) typeNameHandler(handler TypeNameHandleFunction) *RouteBuilder {
  270. b.typeNameHandleFunc = handler
  271. return b
  272. }
  273. // Build creates a new Route using the specification details collected by the RouteBuilder
  274. func (b *RouteBuilder) Build() Route {
  275. pathExpr, err := newPathExpression(b.currentPath)
  276. if err != nil {
  277. log.Printf("Invalid path:%s because:%v", b.currentPath, err)
  278. os.Exit(1)
  279. }
  280. if b.function == nil {
  281. log.Printf("No function specified for route:" + b.currentPath)
  282. os.Exit(1)
  283. }
  284. operationName := b.operation
  285. if len(operationName) == 0 && b.function != nil {
  286. // extract from definition
  287. operationName = nameOfFunction(b.function)
  288. }
  289. route := Route{
  290. Method: b.httpMethod,
  291. Path: concatPath(b.rootPath, b.currentPath),
  292. Produces: b.produces,
  293. Consumes: b.consumes,
  294. Function: b.function,
  295. Filters: b.filters,
  296. If: b.conditions,
  297. relativePath: b.currentPath,
  298. pathExpr: pathExpr,
  299. Doc: b.doc,
  300. Notes: b.notes,
  301. Operation: operationName,
  302. ParameterDocs: b.parameters,
  303. ResponseErrors: b.errorMap,
  304. DefaultResponse: b.defaultResponse,
  305. ReadSample: b.readSample,
  306. WriteSample: b.writeSample,
  307. Metadata: b.metadata,
  308. Deprecated: b.deprecated,
  309. contentEncodingEnabled: b.contentEncodingEnabled,
  310. allowedMethodsWithoutContentType: b.allowedMethodsWithoutContentType,
  311. }
  312. route.Extensions = b.extensions
  313. route.postBuild()
  314. return route
  315. }
  316. func concatPath(path1, path2 string) string {
  317. return strings.TrimRight(path1, "/") + "/" + strings.TrimLeft(path2, "/")
  318. }
  319. var anonymousFuncCount int32
  320. // nameOfFunction returns the short name of the function f for documentation.
  321. // It uses a runtime feature for debugging ; its value may change for later Go versions.
  322. func nameOfFunction(f interface{}) string {
  323. fun := runtime.FuncForPC(reflect.ValueOf(f).Pointer())
  324. tokenized := strings.Split(fun.Name(), ".")
  325. last := tokenized[len(tokenized)-1]
  326. last = strings.TrimSuffix(last, ")·fm") // < Go 1.5
  327. last = strings.TrimSuffix(last, ")-fm") // Go 1.5
  328. last = strings.TrimSuffix(last, "·fm") // < Go 1.5
  329. last = strings.TrimSuffix(last, "-fm") // Go 1.5
  330. if last == "func1" { // this could mean conflicts in API docs
  331. val := atomic.AddInt32(&anonymousFuncCount, 1)
  332. last = "func" + fmt.Sprintf("%d", val)
  333. atomic.StoreInt32(&anonymousFuncCount, val)
  334. }
  335. return last
  336. }