build.go 7.5 KB

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