Export the field names. The JSON codec ignores unexported names.
type Vertex struct {
FirstName int `json:"first-name"`
LastName int `json:"last-name"`
}
To encode, wrap a buffer with an base64 encoder with a JSON encoder:
func encodeToBase64(v interface{}) (string, error) {
var buf bytes.Buffer
encoder := base64.NewEncoder(base64.StdEncoding, &buf)
err := json.NewEncoder(encoder).Encode(v)
if err != nil {
return "", err
}
encoder.Close()
return buf.String(), nil
}
Decode the other way around:
func decodeFromBase64(v interface{}, enc string) error {
return json.NewDecoder(base64.NewDecoder(base64.StdEncoding, strings.NewReader(enc))).Decode(v)
}
Here's an example use of the functions:
v0 := Vertex{1, 2}
enc, err := encodeToBase64(v0)
if err != nil {
log.Fatal(err)
}
fmt.Println(enc)
var v1 Vertex
if err := decodeFromBase64(&v1, enc); err != nil {
log.Fatal(err)
}
Run the example on the GoLang PlayGround.