build.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. // Package xmlutil provides XML serialization of AWS requests and responses.
  2. package xmlutil
  3. import (
  4. "encoding/base64"
  5. "encoding/xml"
  6. "fmt"
  7. "reflect"
  8. "sort"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "github.com/aws/aws-sdk-go/private/protocol"
  13. )
  14. // BuildXML will serialize params into an xml.Encoder. Error will be returned
  15. // if the serialization of any of the params or nested values fails.
  16. func BuildXML(params interface{}, e *xml.Encoder) error {
  17. return buildXML(params, e, false)
  18. }
  19. func buildXML(params interface{}, e *xml.Encoder, sorted bool) error {
  20. b := xmlBuilder{encoder: e, namespaces: map[string]string{}}
  21. root := NewXMLElement(xml.Name{})
  22. if err := b.buildValue(reflect.ValueOf(params), root, ""); err != nil {
  23. return err
  24. }
  25. for _, c := range root.Children {
  26. for _, v := range c {
  27. return StructToXML(e, v, sorted)
  28. }
  29. }
  30. return nil
  31. }
  32. // Returns the reflection element of a value, if it is a pointer.
  33. func elemOf(value reflect.Value) reflect.Value {
  34. for value.Kind() == reflect.Ptr {
  35. value = value.Elem()
  36. }
  37. return value
  38. }
  39. // A xmlBuilder serializes values from Go code to XML
  40. type xmlBuilder struct {
  41. encoder *xml.Encoder
  42. namespaces map[string]string
  43. }
  44. // buildValue generic XMLNode builder for any type. Will build value for their specific type
  45. // struct, list, map, scalar.
  46. //
  47. // Also takes a "type" tag value to set what type a value should be converted to XMLNode as. If
  48. // type is not provided reflect will be used to determine the value's type.
  49. func (b *xmlBuilder) buildValue(value reflect.Value, current *XMLNode, tag reflect.StructTag) error {
  50. value = elemOf(value)
  51. if !value.IsValid() { // no need to handle zero values
  52. return nil
  53. } else if tag.Get("location") != "" { // don't handle non-body location values
  54. return nil
  55. }
  56. xml := tag.Get("xml")
  57. if len(xml) != 0 {
  58. name := strings.SplitAfterN(xml, ",", 2)[0]
  59. if name == "-" {
  60. return nil
  61. }
  62. }
  63. t := tag.Get("type")
  64. if t == "" {
  65. switch value.Kind() {
  66. case reflect.Struct:
  67. t = "structure"
  68. case reflect.Slice:
  69. t = "list"
  70. case reflect.Map:
  71. t = "map"
  72. }
  73. }
  74. switch t {
  75. case "structure":
  76. if field, ok := value.Type().FieldByName("_"); ok {
  77. tag = tag + reflect.StructTag(" ") + field.Tag
  78. }
  79. return b.buildStruct(value, current, tag)
  80. case "list":
  81. return b.buildList(value, current, tag)
  82. case "map":
  83. return b.buildMap(value, current, tag)
  84. default:
  85. return b.buildScalar(value, current, tag)
  86. }
  87. }
  88. // buildStruct adds a struct and its fields to the current XMLNode. All fields and any nested
  89. // types are converted to XMLNodes also.
  90. func (b *xmlBuilder) buildStruct(value reflect.Value, current *XMLNode, tag reflect.StructTag) error {
  91. if !value.IsValid() {
  92. return nil
  93. }
  94. // unwrap payloads
  95. if payload := tag.Get("payload"); payload != "" {
  96. field, _ := value.Type().FieldByName(payload)
  97. tag = field.Tag
  98. value = elemOf(value.FieldByName(payload))
  99. if !value.IsValid() {
  100. return nil
  101. }
  102. }
  103. child := NewXMLElement(xml.Name{Local: tag.Get("locationName")})
  104. // there is an xmlNamespace associated with this struct
  105. if prefix, uri := tag.Get("xmlPrefix"), tag.Get("xmlURI"); uri != "" {
  106. ns := xml.Attr{
  107. Name: xml.Name{Local: "xmlns"},
  108. Value: uri,
  109. }
  110. if prefix != "" {
  111. b.namespaces[prefix] = uri // register the namespace
  112. ns.Name.Local = "xmlns:" + prefix
  113. }
  114. child.Attr = append(child.Attr, ns)
  115. }
  116. var payloadFields, nonPayloadFields int
  117. t := value.Type()
  118. for i := 0; i < value.NumField(); i++ {
  119. member := elemOf(value.Field(i))
  120. field := t.Field(i)
  121. if field.PkgPath != "" {
  122. continue // ignore unexported fields
  123. }
  124. if field.Tag.Get("ignore") != "" {
  125. continue
  126. }
  127. mTag := field.Tag
  128. if mTag.Get("location") != "" { // skip non-body members
  129. nonPayloadFields++
  130. continue
  131. }
  132. payloadFields++
  133. if protocol.CanSetIdempotencyToken(value.Field(i), field) {
  134. token := protocol.GetIdempotencyToken()
  135. member = reflect.ValueOf(token)
  136. }
  137. memberName := mTag.Get("locationName")
  138. if memberName == "" {
  139. memberName = field.Name
  140. mTag = reflect.StructTag(string(mTag) + ` locationName:"` + memberName + `"`)
  141. }
  142. if err := b.buildValue(member, child, mTag); err != nil {
  143. return err
  144. }
  145. }
  146. // Only case where the child shape is not added is if the shape only contains
  147. // non-payload fields, e.g headers/query.
  148. if !(payloadFields == 0 && nonPayloadFields > 0) {
  149. current.AddChild(child)
  150. }
  151. return nil
  152. }
  153. // buildList adds the value's list items to the current XMLNode as children nodes. All
  154. // nested values in the list are converted to XMLNodes also.
  155. func (b *xmlBuilder) buildList(value reflect.Value, current *XMLNode, tag reflect.StructTag) error {
  156. if value.IsNil() { // don't build omitted lists
  157. return nil
  158. }
  159. // check for unflattened list member
  160. flattened := tag.Get("flattened") != ""
  161. xname := xml.Name{Local: tag.Get("locationName")}
  162. if flattened {
  163. for i := 0; i < value.Len(); i++ {
  164. child := NewXMLElement(xname)
  165. current.AddChild(child)
  166. if err := b.buildValue(value.Index(i), child, ""); err != nil {
  167. return err
  168. }
  169. }
  170. } else {
  171. list := NewXMLElement(xname)
  172. current.AddChild(list)
  173. for i := 0; i < value.Len(); i++ {
  174. iname := tag.Get("locationNameList")
  175. if iname == "" {
  176. iname = "member"
  177. }
  178. child := NewXMLElement(xml.Name{Local: iname})
  179. list.AddChild(child)
  180. if err := b.buildValue(value.Index(i), child, ""); err != nil {
  181. return err
  182. }
  183. }
  184. }
  185. return nil
  186. }
  187. // buildMap adds the value's key/value pairs to the current XMLNode as children nodes. All
  188. // nested values in the map are converted to XMLNodes also.
  189. //
  190. // Error will be returned if it is unable to build the map's values into XMLNodes
  191. func (b *xmlBuilder) buildMap(value reflect.Value, current *XMLNode, tag reflect.StructTag) error {
  192. if value.IsNil() { // don't build omitted maps
  193. return nil
  194. }
  195. maproot := NewXMLElement(xml.Name{Local: tag.Get("locationName")})
  196. current.AddChild(maproot)
  197. current = maproot
  198. kname, vname := "key", "value"
  199. if n := tag.Get("locationNameKey"); n != "" {
  200. kname = n
  201. }
  202. if n := tag.Get("locationNameValue"); n != "" {
  203. vname = n
  204. }
  205. // sorting is not required for compliance, but it makes testing easier
  206. keys := make([]string, value.Len())
  207. for i, k := range value.MapKeys() {
  208. keys[i] = k.String()
  209. }
  210. sort.Strings(keys)
  211. for _, k := range keys {
  212. v := value.MapIndex(reflect.ValueOf(k))
  213. mapcur := current
  214. if tag.Get("flattened") == "" { // add "entry" tag to non-flat maps
  215. child := NewXMLElement(xml.Name{Local: "entry"})
  216. mapcur.AddChild(child)
  217. mapcur = child
  218. }
  219. kchild := NewXMLElement(xml.Name{Local: kname})
  220. kchild.Text = k
  221. vchild := NewXMLElement(xml.Name{Local: vname})
  222. mapcur.AddChild(kchild)
  223. mapcur.AddChild(vchild)
  224. if err := b.buildValue(v, vchild, ""); err != nil {
  225. return err
  226. }
  227. }
  228. return nil
  229. }
  230. // buildScalar will convert the value into a string and append it as a attribute or child
  231. // of the current XMLNode.
  232. //
  233. // The value will be added as an attribute if tag contains a "xmlAttribute" attribute value.
  234. //
  235. // Error will be returned if the value type is unsupported.
  236. func (b *xmlBuilder) buildScalar(value reflect.Value, current *XMLNode, tag reflect.StructTag) error {
  237. var str string
  238. switch converted := value.Interface().(type) {
  239. case string:
  240. str = converted
  241. case []byte:
  242. if !value.IsNil() {
  243. str = base64.StdEncoding.EncodeToString(converted)
  244. }
  245. case bool:
  246. str = strconv.FormatBool(converted)
  247. case int64:
  248. str = strconv.FormatInt(converted, 10)
  249. case int:
  250. str = strconv.Itoa(converted)
  251. case float64:
  252. str = strconv.FormatFloat(converted, 'f', -1, 64)
  253. case float32:
  254. str = strconv.FormatFloat(float64(converted), 'f', -1, 32)
  255. case time.Time:
  256. format := tag.Get("timestampFormat")
  257. if len(format) == 0 {
  258. format = protocol.ISO8601TimeFormatName
  259. }
  260. str = protocol.FormatTime(format, converted)
  261. default:
  262. return fmt.Errorf("unsupported value for param %s: %v (%s)",
  263. tag.Get("locationName"), value.Interface(), value.Type().Name())
  264. }
  265. xname := xml.Name{Local: tag.Get("locationName")}
  266. if tag.Get("xmlAttribute") != "" { // put into current node's attribute list
  267. attr := xml.Attr{Name: xname, Value: str}
  268. current.Attr = append(current.Attr, attr)
  269. } else { // regular text node
  270. current.AddChild(&XMLNode{Name: xname, Text: str})
  271. }
  272. return nil
  273. }