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