restjson.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // Package restjson provides RESTful JSON serialisation of AWS
  2. // requests and responses.
  3. package restjson
  4. //go:generate go run ../../fixtures/protocol/generate.go ../../fixtures/protocol/input/rest-json.json build_test.go
  5. //go:generate go run ../../fixtures/protocol/generate.go ../../fixtures/protocol/output/rest-json.json unmarshal_test.go
  6. import (
  7. "encoding/json"
  8. "io/ioutil"
  9. "strings"
  10. "github.com/aws/aws-sdk-go/aws/awserr"
  11. "github.com/aws/aws-sdk-go/aws/request"
  12. "github.com/aws/aws-sdk-go/internal/protocol/jsonrpc"
  13. "github.com/aws/aws-sdk-go/internal/protocol/rest"
  14. )
  15. // Build builds a request for the REST JSON protocol.
  16. func Build(r *request.Request) {
  17. rest.Build(r)
  18. if t := rest.PayloadType(r.Params); t == "structure" || t == "" {
  19. jsonrpc.Build(r)
  20. }
  21. }
  22. // Unmarshal unmarshals a response body for the REST JSON protocol.
  23. func Unmarshal(r *request.Request) {
  24. if t := rest.PayloadType(r.Data); t == "structure" || t == "" {
  25. jsonrpc.Unmarshal(r)
  26. } else {
  27. rest.Unmarshal(r)
  28. }
  29. }
  30. // UnmarshalMeta unmarshals response headers for the REST JSON protocol.
  31. func UnmarshalMeta(r *request.Request) {
  32. rest.UnmarshalMeta(r)
  33. }
  34. // UnmarshalError unmarshals a response error for the REST JSON protocol.
  35. func UnmarshalError(r *request.Request) {
  36. code := r.HTTPResponse.Header.Get("X-Amzn-Errortype")
  37. bodyBytes, err := ioutil.ReadAll(r.HTTPResponse.Body)
  38. if err != nil {
  39. r.Error = awserr.New("SerializationError", "failed reading REST JSON error response", err)
  40. return
  41. }
  42. if len(bodyBytes) == 0 {
  43. r.Error = awserr.NewRequestFailure(
  44. awserr.New("SerializationError", r.HTTPResponse.Status, nil),
  45. r.HTTPResponse.StatusCode,
  46. "",
  47. )
  48. return
  49. }
  50. var jsonErr jsonErrorResponse
  51. if err := json.Unmarshal(bodyBytes, &jsonErr); err != nil {
  52. r.Error = awserr.New("SerializationError", "failed decoding REST JSON error response", err)
  53. return
  54. }
  55. if code == "" {
  56. code = jsonErr.Code
  57. }
  58. codes := strings.SplitN(code, ":", 2)
  59. r.Error = awserr.NewRequestFailure(
  60. awserr.New(codes[0], jsonErr.Message, nil),
  61. r.HTTPResponse.StatusCode,
  62. r.RequestID,
  63. )
  64. }
  65. type jsonErrorResponse struct {
  66. Code string `json:"code"`
  67. Message string `json:"message"`
  68. }