route_builder.go 12 KB

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