build.go 7.6 KB

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