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