build.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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. if field.Tag.Get("ignore") != "" {
  114. continue
  115. }
  116. mTag := field.Tag
  117. if mTag.Get("location") != "" { // skip non-body members
  118. continue
  119. }
  120. if protocol.CanSetIdempotencyToken(value.Field(i), field) {
  121. token := protocol.GetIdempotencyToken()
  122. member = reflect.ValueOf(token)
  123. }
  124. memberName := mTag.Get("locationName")
  125. if memberName == "" {
  126. memberName = field.Name
  127. mTag = reflect.StructTag(string(mTag) + ` locationName:"` + memberName + `"`)
  128. }
  129. if err := b.buildValue(member, child, mTag); err != nil {
  130. return err
  131. }
  132. fieldAdded = true
  133. }
  134. if fieldAdded { // only append this child if we have one ore more valid members
  135. current.AddChild(child)
  136. }
  137. return nil
  138. }
  139. // buildList adds the value's list items to the current XMLNode as children nodes. All
  140. // nested values in the list are converted to XMLNodes also.
  141. func (b *xmlBuilder) buildList(value reflect.Value, current *XMLNode, tag reflect.StructTag) error {
  142. if value.IsNil() { // don't build omitted lists
  143. return nil
  144. }
  145. // check for unflattened list member
  146. flattened := tag.Get("flattened") != ""
  147. xname := xml.Name{Local: tag.Get("locationName")}
  148. if flattened {
  149. for i := 0; i < value.Len(); i++ {
  150. child := NewXMLElement(xname)
  151. current.AddChild(child)
  152. if err := b.buildValue(value.Index(i), child, ""); err != nil {
  153. return err
  154. }
  155. }
  156. } else {
  157. list := NewXMLElement(xname)
  158. current.AddChild(list)
  159. for i := 0; i < value.Len(); i++ {
  160. iname := tag.Get("locationNameList")
  161. if iname == "" {
  162. iname = "member"
  163. }
  164. child := NewXMLElement(xml.Name{Local: iname})
  165. list.AddChild(child)
  166. if err := b.buildValue(value.Index(i), child, ""); err != nil {
  167. return err
  168. }
  169. }
  170. }
  171. return nil
  172. }
  173. // buildMap adds the value's key/value pairs to the current XMLNode as children nodes. All
  174. // nested values in the map are converted to XMLNodes also.
  175. //
  176. // Error will be returned if it is unable to build the map's values into XMLNodes
  177. func (b *xmlBuilder) buildMap(value reflect.Value, current *XMLNode, tag reflect.StructTag) error {
  178. if value.IsNil() { // don't build omitted maps
  179. return nil
  180. }
  181. maproot := NewXMLElement(xml.Name{Local: tag.Get("locationName")})
  182. current.AddChild(maproot)
  183. current = maproot
  184. kname, vname := "key", "value"
  185. if n := tag.Get("locationNameKey"); n != "" {
  186. kname = n
  187. }
  188. if n := tag.Get("locationNameValue"); n != "" {
  189. vname = n
  190. }
  191. // sorting is not required for compliance, but it makes testing easier
  192. keys := make([]string, value.Len())
  193. for i, k := range value.MapKeys() {
  194. keys[i] = k.String()
  195. }
  196. sort.Strings(keys)
  197. for _, k := range keys {
  198. v := value.MapIndex(reflect.ValueOf(k))
  199. mapcur := current
  200. if tag.Get("flattened") == "" { // add "entry" tag to non-flat maps
  201. child := NewXMLElement(xml.Name{Local: "entry"})
  202. mapcur.AddChild(child)
  203. mapcur = child
  204. }
  205. kchild := NewXMLElement(xml.Name{Local: kname})
  206. kchild.Text = k
  207. vchild := NewXMLElement(xml.Name{Local: vname})
  208. mapcur.AddChild(kchild)
  209. mapcur.AddChild(vchild)
  210. if err := b.buildValue(v, vchild, ""); err != nil {
  211. return err
  212. }
  213. }
  214. return nil
  215. }
  216. // buildScalar will convert the value into a string and append it as a attribute or child
  217. // of the current XMLNode.
  218. //
  219. // The value will be added as an attribute if tag contains a "xmlAttribute" attribute value.
  220. //
  221. // Error will be returned if the value type is unsupported.
  222. func (b *xmlBuilder) buildScalar(value reflect.Value, current *XMLNode, tag reflect.StructTag) error {
  223. var str string
  224. switch converted := value.Interface().(type) {
  225. case string:
  226. str = converted
  227. case []byte:
  228. if !value.IsNil() {
  229. str = base64.StdEncoding.EncodeToString(converted)
  230. }
  231. case bool:
  232. str = strconv.FormatBool(converted)
  233. case int64:
  234. str = strconv.FormatInt(converted, 10)
  235. case int:
  236. str = strconv.Itoa(converted)
  237. case float64:
  238. str = strconv.FormatFloat(converted, 'f', -1, 64)
  239. case float32:
  240. str = strconv.FormatFloat(float64(converted), 'f', -1, 32)
  241. case time.Time:
  242. const ISO8601UTC = "2006-01-02T15:04:05Z"
  243. str = converted.UTC().Format(ISO8601UTC)
  244. default:
  245. return fmt.Errorf("unsupported value for param %s: %v (%s)",
  246. tag.Get("locationName"), value.Interface(), value.Type().Name())
  247. }
  248. xname := xml.Name{Local: tag.Get("locationName")}
  249. if tag.Get("xmlAttribute") != "" { // put into current node's attribute list
  250. attr := xml.Attr{Name: xname, Value: str}
  251. current.Attr = append(current.Attr, attr)
  252. } else { // regular text node
  253. current.AddChild(&XMLNode{Name: xname, Text: str})
  254. }
  255. return nil
  256. }