jsonvalue.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package protocol
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "fmt"
  6. "strconv"
  7. "github.com/aws/aws-sdk-go/aws"
  8. )
  9. // EscapeMode is the mode that should be use for escaping a value
  10. type EscapeMode uint
  11. // The modes for escaping a value before it is marshaled, and unmarshaled.
  12. const (
  13. NoEscape EscapeMode = iota
  14. Base64Escape
  15. QuotedEscape
  16. )
  17. // EncodeJSONValue marshals the value into a JSON string, and optionally base64
  18. // encodes the string before returning it.
  19. //
  20. // Will panic if the escape mode is unknown.
  21. func EncodeJSONValue(v aws.JSONValue, escape EscapeMode) (string, error) {
  22. b, err := json.Marshal(v)
  23. if err != nil {
  24. return "", err
  25. }
  26. switch escape {
  27. case NoEscape:
  28. return string(b), nil
  29. case Base64Escape:
  30. return base64.StdEncoding.EncodeToString(b), nil
  31. case QuotedEscape:
  32. return strconv.Quote(string(b)), nil
  33. }
  34. panic(fmt.Sprintf("EncodeJSONValue called with unknown EscapeMode, %v", escape))
  35. }
  36. // DecodeJSONValue will attempt to decode the string input as a JSONValue.
  37. // Optionally decoding base64 the value first before JSON unmarshaling.
  38. //
  39. // Will panic if the escape mode is unknown.
  40. func DecodeJSONValue(v string, escape EscapeMode) (aws.JSONValue, error) {
  41. var b []byte
  42. var err error
  43. switch escape {
  44. case NoEscape:
  45. b = []byte(v)
  46. case Base64Escape:
  47. b, err = base64.StdEncoding.DecodeString(v)
  48. case QuotedEscape:
  49. var u string
  50. u, err = strconv.Unquote(v)
  51. b = []byte(u)
  52. default:
  53. panic(fmt.Sprintf("DecodeJSONValue called with unknown EscapeMode, %v", escape))
  54. }
  55. if err != nil {
  56. return nil, err
  57. }
  58. m := aws.JSONValue{}
  59. err = json.Unmarshal(b, &m)
  60. if err != nil {
  61. return nil, err
  62. }
  63. return m, nil
  64. }