route_builder.go 10 KB

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