restjson.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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/ks3sdklib/aws-sdk-go/aws"
  11. "github.com/ks3sdklib/aws-sdk-go/internal/apierr"
  12. "github.com/ks3sdklib/aws-sdk-go/internal/protocol/jsonrpc"
  13. "github.com/ks3sdklib/aws-sdk-go/internal/protocol/rest"
  14. )
  15. // Build builds a request for the REST JSON protocol.
  16. func Build(r *aws.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 *aws.Request) {
  24. if t := rest.PayloadType(r.Data); t == "structure" || t == "" {
  25. jsonrpc.Unmarshal(r)
  26. }
  27. }
  28. // UnmarshalMeta unmarshals response headers for the REST JSON protocol.
  29. func UnmarshalMeta(r *aws.Request) {
  30. rest.Unmarshal(r)
  31. }
  32. // UnmarshalError unmarshals a response error for the REST JSON protocol.
  33. func UnmarshalError(r *aws.Request) {
  34. code := r.HTTPResponse.Header.Get("X-Amzn-Errortype")
  35. bodyBytes, err := ioutil.ReadAll(r.HTTPResponse.Body)
  36. if err != nil {
  37. r.Error = apierr.New("Unmarshal", "failed reading REST JSON error response", err)
  38. return
  39. }
  40. if len(bodyBytes) == 0 {
  41. r.Error = apierr.NewRequestError(
  42. apierr.New("Unmarshal", r.HTTPResponse.Status, nil),
  43. r.HTTPResponse.StatusCode,
  44. "",
  45. )
  46. return
  47. }
  48. var jsonErr jsonErrorResponse
  49. if err := json.Unmarshal(bodyBytes, &jsonErr); err != nil {
  50. r.Error = apierr.New("Unmarshal", "failed decoding REST JSON error response", err)
  51. return
  52. }
  53. if code == "" {
  54. code = jsonErr.Code
  55. }
  56. codes := strings.SplitN(code, ":", 2)
  57. r.Error = apierr.NewRequestError(
  58. apierr.New(codes[0], jsonErr.Message, nil),
  59. r.HTTPResponse.StatusCode,
  60. "",
  61. )
  62. }
  63. type jsonErrorResponse struct {
  64. Code string `json:"code"`
  65. Message string `json:"message"`
  66. }