How to convert struct to base64 encoded string and viceversa

Viewed 2898

Given an instance of a struct, I want to convert it into a base64 encoded string. And also decode it back into a struct.

I have so far tried this for the encoding: https://play.golang.org/p/tLLQzEXAnBC but keep running into the following errors:

./prog.go:18:20: v.JSON undefined (type Vertex has no field or method JSON)
./prog.go:33:9: undefined: Base64

Where am I going wrong?

1 Answers

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.

Related