build.go 8.0 KB

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