operation.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. // +build codegen
  2. package api
  3. import (
  4. "bytes"
  5. "fmt"
  6. "regexp"
  7. "sort"
  8. "strings"
  9. "text/template"
  10. )
  11. // An Operation defines a specific API Operation.
  12. type Operation struct {
  13. API *API `json:"-"`
  14. ExportedName string
  15. Name string
  16. Documentation string
  17. HTTP HTTPInfo
  18. InputRef ShapeRef `json:"input"`
  19. OutputRef ShapeRef `json:"output"`
  20. ErrorRefs []ShapeRef `json:"errors"`
  21. Paginator *Paginator
  22. Deprecated bool `json:"deprecated"`
  23. AuthType string `json:"authtype"`
  24. }
  25. // A HTTPInfo defines the method of HTTP request for the Operation.
  26. type HTTPInfo struct {
  27. Method string
  28. RequestURI string
  29. ResponseCode uint
  30. }
  31. // HasInput returns if the Operation accepts an input paramater
  32. func (o *Operation) HasInput() bool {
  33. return o.InputRef.ShapeName != ""
  34. }
  35. // HasOutput returns if the Operation accepts an output parameter
  36. func (o *Operation) HasOutput() bool {
  37. return o.OutputRef.ShapeName != ""
  38. }
  39. // tplOperation defines a template for rendering an API Operation
  40. var tplOperation = template.Must(template.New("operation").Parse(`
  41. const op{{ .ExportedName }} = "{{ .Name }}"
  42. // {{ .ExportedName }}Request generates a "aws/request.Request" representing the
  43. // client's request for the {{ .ExportedName }} operation. The "output" return
  44. // value can be used to capture response data after the request's "Send" method
  45. // is called.
  46. //
  47. // See {{ .ExportedName }} for usage and error information.
  48. //
  49. // Creating a request object using this method should be used when you want to inject
  50. // custom logic into the request's lifecycle using a custom handler, or if you want to
  51. // access properties on the request object before or after sending the request. If
  52. // you just want the service response, call the {{ .ExportedName }} method directly
  53. // instead.
  54. //
  55. // Note: You must call the "Send" method on the returned request object in order
  56. // to execute the request.
  57. //
  58. // // Example sending a request using the {{ .ExportedName }}Request method.
  59. // req, resp := client.{{ .ExportedName }}Request(params)
  60. //
  61. // err := req.Send()
  62. // if err == nil { // resp is now filled
  63. // fmt.Println(resp)
  64. // }
  65. //
  66. func (c *{{ .API.StructName }}) {{ .ExportedName }}Request(` +
  67. `input {{ .InputRef.GoType }}) (req *request.Request, output {{ .OutputRef.GoType }}) {
  68. {{ if (or .Deprecated (or .InputRef.Deprecated .OutputRef.Deprecated)) }}if c.Client.Config.Logger != nil {
  69. c.Client.Config.Logger.Log("This operation, {{ .ExportedName }}, has been deprecated")
  70. }
  71. op := &request.Operation{ {{ else }} op := &request.Operation{ {{ end }}
  72. Name: op{{ .ExportedName }},
  73. {{ if ne .HTTP.Method "" }}HTTPMethod: "{{ .HTTP.Method }}",
  74. {{ end }}HTTPPath: {{ if ne .HTTP.RequestURI "" }}"{{ .HTTP.RequestURI }}"{{ else }}"/"{{ end }},
  75. {{ if .Paginator }}Paginator: &request.Paginator{
  76. InputTokens: {{ .Paginator.InputTokensString }},
  77. OutputTokens: {{ .Paginator.OutputTokensString }},
  78. LimitToken: "{{ .Paginator.LimitKey }}",
  79. TruncationToken: "{{ .Paginator.MoreResults }}",
  80. },
  81. {{ end }}
  82. }
  83. if input == nil {
  84. input = &{{ .InputRef.GoTypeElem }}{}
  85. }
  86. req = c.newRequest(op, input, output){{ if eq .OutputRef.Shape.Placeholder true }}
  87. req.Handlers.Unmarshal.Remove({{ .API.ProtocolPackage }}.UnmarshalHandler)
  88. req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler){{ end }}
  89. {{ if eq .AuthType "none" }}req.Config.Credentials = credentials.AnonymousCredentials
  90. output = &{{ .OutputRef.GoTypeElem }}{} {{ else }} output = &{{ .OutputRef.GoTypeElem }}{} {{ end }}
  91. req.Data = output
  92. return
  93. }
  94. // {{ .ExportedName }} API operation for {{ .API.Metadata.ServiceFullName }}.
  95. {{ if .Documentation -}}
  96. //
  97. {{ .Documentation }}
  98. {{ end -}}
  99. //
  100. // Returns awserr.Error for service API and SDK errors. Use runtime type assertions
  101. // with awserr.Error's Code and Message methods to get detailed information about
  102. // the error.
  103. //
  104. // See the AWS API reference guide for {{ .API.Metadata.ServiceFullName }}'s
  105. // API operation {{ .ExportedName }} for usage and error information.
  106. {{ if .ErrorRefs -}}
  107. //
  108. // Returned Error Codes:
  109. {{ range $_, $err := .ErrorRefs -}}
  110. {{ $errDoc := $err.IndentedDocstring -}}
  111. // * {{ $err.Shape.ErrorName }}
  112. {{ if $errDoc -}}
  113. {{ $errDoc }}{{ end }}
  114. //
  115. {{ end -}}
  116. {{ end -}}
  117. func (c *{{ .API.StructName }}) {{ .ExportedName }}(` +
  118. `input {{ .InputRef.GoType }}) ({{ .OutputRef.GoType }}, error) {
  119. req, out := c.{{ .ExportedName }}Request(input)
  120. err := req.Send()
  121. return out, err
  122. }
  123. {{ if .Paginator }}
  124. // {{ .ExportedName }}Pages iterates over the pages of a {{ .ExportedName }} operation,
  125. // calling the "fn" function with the response data for each page. To stop
  126. // iterating, return false from the fn function.
  127. //
  128. // See {{ .ExportedName }} method for more information on how to use this operation.
  129. //
  130. // Note: This operation can generate multiple requests to a service.
  131. //
  132. // // Example iterating over at most 3 pages of a {{ .ExportedName }} operation.
  133. // pageNum := 0
  134. // err := client.{{ .ExportedName }}Pages(params,
  135. // func(page {{ .OutputRef.GoType }}, lastPage bool) bool {
  136. // pageNum++
  137. // fmt.Println(page)
  138. // return pageNum <= 3
  139. // })
  140. //
  141. func (c *{{ .API.StructName }}) {{ .ExportedName }}Pages(` +
  142. `input {{ .InputRef.GoType }}, fn func(p {{ .OutputRef.GoType }}, lastPage bool) (shouldContinue bool)) error {
  143. page, _ := c.{{ .ExportedName }}Request(input)
  144. page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator"))
  145. return page.EachPage(func(p interface{}, lastPage bool) bool {
  146. return fn(p.({{ .OutputRef.GoType }}), lastPage)
  147. })
  148. }
  149. {{ end }}
  150. `))
  151. // GoCode returns a string of rendered GoCode for this Operation
  152. func (o *Operation) GoCode() string {
  153. var buf bytes.Buffer
  154. err := tplOperation.Execute(&buf, o)
  155. if err != nil {
  156. panic(err)
  157. }
  158. return strings.TrimSpace(buf.String())
  159. }
  160. // tplInfSig defines the template for rendering an Operation's signature within an Interface definition.
  161. var tplInfSig = template.Must(template.New("opsig").Parse(`
  162. {{ .ExportedName }}Request({{ .InputRef.GoTypeWithPkgName }}) (*request.Request, {{ .OutputRef.GoTypeWithPkgName }})
  163. {{ .ExportedName }}({{ .InputRef.GoTypeWithPkgName }}) ({{ .OutputRef.GoTypeWithPkgName }}, error)
  164. {{ if .Paginator -}}
  165. {{ .ExportedName }}Pages({{ .InputRef.GoTypeWithPkgName }}, func({{ .OutputRef.GoTypeWithPkgName }}, bool) bool) error
  166. {{- end }}
  167. `))
  168. // InterfaceSignature returns a string representing the Operation's interface{}
  169. // functional signature.
  170. func (o *Operation) InterfaceSignature() string {
  171. var buf bytes.Buffer
  172. err := tplInfSig.Execute(&buf, o)
  173. if err != nil {
  174. panic(err)
  175. }
  176. return strings.TrimSpace(buf.String())
  177. }
  178. // tplExample defines the template for rendering an Operation example
  179. var tplExample = template.Must(template.New("operationExample").Parse(`
  180. func Example{{ .API.StructName }}_{{ .ExportedName }}() {
  181. sess, err := session.NewSession()
  182. if err != nil {
  183. fmt.Println("failed to create session,", err)
  184. return
  185. }
  186. svc := {{ .API.PackageName }}.New(sess)
  187. {{ .ExampleInput }}
  188. resp, err := svc.{{ .ExportedName }}(params)
  189. if err != nil {
  190. // Print the error, cast err to awserr.Error to get the Code and
  191. // Message from an error.
  192. fmt.Println(err.Error())
  193. return
  194. }
  195. // Pretty-print the response data.
  196. fmt.Println(resp)
  197. }
  198. `))
  199. // Example returns a string of the rendered Go code for the Operation
  200. func (o *Operation) Example() string {
  201. var buf bytes.Buffer
  202. err := tplExample.Execute(&buf, o)
  203. if err != nil {
  204. panic(err)
  205. }
  206. return strings.TrimSpace(buf.String())
  207. }
  208. // ExampleInput return a string of the rendered Go code for an example's input parameters
  209. func (o *Operation) ExampleInput() string {
  210. if len(o.InputRef.Shape.MemberRefs) == 0 {
  211. return fmt.Sprintf("var params *%s.%s",
  212. o.API.PackageName(), o.InputRef.GoTypeElem())
  213. }
  214. e := example{o, map[string]int{}}
  215. return "params := " + e.traverseAny(o.InputRef.Shape, false, false)
  216. }
  217. // A example provides
  218. type example struct {
  219. *Operation
  220. visited map[string]int
  221. }
  222. // traverseAny returns rendered Go code for the shape.
  223. func (e *example) traverseAny(s *Shape, required, payload bool) string {
  224. str := ""
  225. e.visited[s.ShapeName]++
  226. switch s.Type {
  227. case "structure":
  228. str = e.traverseStruct(s, required, payload)
  229. case "list":
  230. str = e.traverseList(s, required, payload)
  231. case "map":
  232. str = e.traverseMap(s, required, payload)
  233. default:
  234. str = e.traverseScalar(s, required, payload)
  235. }
  236. e.visited[s.ShapeName]--
  237. return str
  238. }
  239. var reType = regexp.MustCompile(`\b([A-Z])`)
  240. // traverseStruct returns rendered Go code for a structure type shape.
  241. func (e *example) traverseStruct(s *Shape, required, payload bool) string {
  242. var buf bytes.Buffer
  243. buf.WriteString("&" + s.API.PackageName() + "." + s.GoTypeElem() + "{")
  244. if required {
  245. buf.WriteString(" // Required")
  246. }
  247. buf.WriteString("\n")
  248. req := make([]string, len(s.Required))
  249. copy(req, s.Required)
  250. sort.Strings(req)
  251. if e.visited[s.ShapeName] < 2 {
  252. for _, n := range req {
  253. m := s.MemberRefs[n].Shape
  254. p := n == s.Payload && (s.MemberRefs[n].Streaming || m.Streaming)
  255. buf.WriteString(n + ": " + e.traverseAny(m, true, p) + ",")
  256. if m.Type != "list" && m.Type != "structure" && m.Type != "map" {
  257. buf.WriteString(" // Required")
  258. }
  259. buf.WriteString("\n")
  260. }
  261. for _, n := range s.MemberNames() {
  262. if s.IsRequired(n) {
  263. continue
  264. }
  265. m := s.MemberRefs[n].Shape
  266. p := n == s.Payload && (s.MemberRefs[n].Streaming || m.Streaming)
  267. buf.WriteString(n + ": " + e.traverseAny(m, false, p) + ",\n")
  268. }
  269. } else {
  270. buf.WriteString("// Recursive values...\n")
  271. }
  272. buf.WriteString("}")
  273. return buf.String()
  274. }
  275. // traverseMap returns rendered Go code for a map type shape.
  276. func (e *example) traverseMap(s *Shape, required, payload bool) string {
  277. var buf bytes.Buffer
  278. t := reType.ReplaceAllString(s.GoTypeElem(), s.API.PackageName()+".$1")
  279. buf.WriteString(t + "{")
  280. if required {
  281. buf.WriteString(" // Required")
  282. }
  283. buf.WriteString("\n")
  284. if e.visited[s.ShapeName] < 2 {
  285. m := s.ValueRef.Shape
  286. buf.WriteString("\"Key\": " + e.traverseAny(m, true, false) + ",")
  287. if m.Type != "list" && m.Type != "structure" && m.Type != "map" {
  288. buf.WriteString(" // Required")
  289. }
  290. buf.WriteString("\n// More values...\n")
  291. } else {
  292. buf.WriteString("// Recursive values...\n")
  293. }
  294. buf.WriteString("}")
  295. return buf.String()
  296. }
  297. // traverseList returns rendered Go code for a list type shape.
  298. func (e *example) traverseList(s *Shape, required, payload bool) string {
  299. var buf bytes.Buffer
  300. t := reType.ReplaceAllString(s.GoTypeElem(), s.API.PackageName()+".$1")
  301. buf.WriteString(t + "{")
  302. if required {
  303. buf.WriteString(" // Required")
  304. }
  305. buf.WriteString("\n")
  306. if e.visited[s.ShapeName] < 2 {
  307. m := s.MemberRef.Shape
  308. buf.WriteString(e.traverseAny(m, true, false) + ",")
  309. if m.Type != "list" && m.Type != "structure" && m.Type != "map" {
  310. buf.WriteString(" // Required")
  311. }
  312. buf.WriteString("\n// More values...\n")
  313. } else {
  314. buf.WriteString("// Recursive values...\n")
  315. }
  316. buf.WriteString("}")
  317. return buf.String()
  318. }
  319. // traverseScalar returns an AWS Type string representation initialized to a value.
  320. // Will panic if s is an unsupported shape type.
  321. func (e *example) traverseScalar(s *Shape, required, payload bool) string {
  322. str := ""
  323. switch s.Type {
  324. case "integer", "long":
  325. str = `aws.Int64(1)`
  326. case "float", "double":
  327. str = `aws.Float64(1.0)`
  328. case "string", "character":
  329. str = `aws.String("` + s.ShapeName + `")`
  330. case "blob":
  331. if payload {
  332. str = `bytes.NewReader([]byte("PAYLOAD"))`
  333. } else {
  334. str = `[]byte("PAYLOAD")`
  335. }
  336. case "boolean":
  337. str = `aws.Bool(true)`
  338. case "timestamp":
  339. str = `aws.Time(time.Now())`
  340. default:
  341. panic("unsupported shape " + s.Type)
  342. }
  343. return str
  344. }