Created
January 22, 2019 14:22
-
-
Save zer09/818b08c761763e42f8b1bc5c753dc065 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// source: https://play.golang.org/p/mJPMN1_KSv | |
// so: https://stackoverflow.com/questions/23003793/convert-arbitrary-golang-interface-to-byte-array | |
package main | |
import ( | |
"bytes" | |
"encoding/gob" | |
"fmt" | |
) | |
type Profile struct { | |
Name string | |
Age int | |
} | |
func main() { | |
// --- encode --- | |
profile := &Profile{ | |
Name: "Roman", | |
Age: 30, | |
} | |
bts, err := getBytes(profile) | |
if err != nil { | |
fmt.Println(err.Error()) | |
return | |
} | |
// --- decode --- | |
var decodedProfile Profile | |
err = getInterface(bts, &decodedProfile) | |
if err != nil { | |
fmt.Println(err.Error()) | |
return | |
} | |
fmt.Println(decodedProfile.Name) | |
} | |
func getBytes(data interface{}) ([]byte, error) { | |
var buf bytes.Buffer | |
enc := gob.NewEncoder(&buf) | |
err := enc.Encode(data) | |
if err != nil { | |
return nil, err | |
} | |
return buf.Bytes(), nil | |
} | |
func getInterface(bts []byte, data interface{}) error { | |
buf := bytes.NewBuffer(bts) | |
dec := gob.NewDecoder(buf) | |
err := dec.Decode(data) | |
if err != nil { | |
return err | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment