1package objx
2
3import (
4	"bytes"
5	"encoding/base64"
6	"encoding/json"
7	"errors"
8	"fmt"
9	"net/url"
10)
11
12// JSON converts the contained object to a JSON string
13// representation
14func (m Map) JSON() (string, error) {
15
16	result, err := json.Marshal(m)
17
18	if err != nil {
19		err = errors.New("objx: JSON encode failed with: " + err.Error())
20	}
21
22	return string(result), err
23
24}
25
26// MustJSON converts the contained object to a JSON string
27// representation and panics if there is an error
28func (m Map) MustJSON() string {
29	result, err := m.JSON()
30	if err != nil {
31		panic(err.Error())
32	}
33	return result
34}
35
36// Base64 converts the contained object to a Base64 string
37// representation of the JSON string representation
38func (m Map) Base64() (string, error) {
39
40	var buf bytes.Buffer
41
42	jsonData, err := m.JSON()
43	if err != nil {
44		return "", err
45	}
46
47	encoder := base64.NewEncoder(base64.StdEncoding, &buf)
48	encoder.Write([]byte(jsonData))
49	encoder.Close()
50
51	return buf.String(), nil
52
53}
54
55// MustBase64 converts the contained object to a Base64 string
56// representation of the JSON string representation and panics
57// if there is an error
58func (m Map) MustBase64() string {
59	result, err := m.Base64()
60	if err != nil {
61		panic(err.Error())
62	}
63	return result
64}
65
66// SignedBase64 converts the contained object to a Base64 string
67// representation of the JSON string representation and signs it
68// using the provided key.
69func (m Map) SignedBase64(key string) (string, error) {
70
71	base64, err := m.Base64()
72	if err != nil {
73		return "", err
74	}
75
76	sig := HashWithKey(base64, key)
77
78	return base64 + SignatureSeparator + sig, nil
79
80}
81
82// MustSignedBase64 converts the contained object to a Base64 string
83// representation of the JSON string representation and signs it
84// using the provided key and panics if there is an error
85func (m Map) MustSignedBase64(key string) string {
86	result, err := m.SignedBase64(key)
87	if err != nil {
88		panic(err.Error())
89	}
90	return result
91}
92
93/*
94	URL Query
95	------------------------------------------------
96*/
97
98// URLValues creates a url.Values object from an Obj. This
99// function requires that the wrapped object be a map[string]interface{}
100func (m Map) URLValues() url.Values {
101
102	vals := make(url.Values)
103
104	for k, v := range m {
105		//TODO: can this be done without sprintf?
106		vals.Set(k, fmt.Sprintf("%v", v))
107	}
108
109	return vals
110}
111
112// URLQuery gets an encoded URL query representing the given
113// Obj. This function requires that the wrapped object be a
114// map[string]interface{}
115func (m Map) URLQuery() (string, error) {
116	return m.URLValues().Encode(), nil
117}
118