Skip to content

Instantly share code, notes, and snippets.

@kjk
Created November 5, 2019 21:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kjk/f6ceb3c30ebdc1e9eb8a695f328251d3 to your computer and use it in GitHub Desktop.
Save kjk/f6ceb3c30ebdc1e9eb8a695f328251d3 to your computer and use it in GitHub Desktop.
Encode data to file and decode from file
// :collection Essential Go
package main
import (
"encoding/gob"
"os"
"log"
"fmt"
)
// :show start
type User struct {
Username string
Password string
}
// :show end
// :show start
func writeToGob(path string, user *User) error {
file, err := os.Create(path)
if err != nil {
return err
}
encoder := gob.NewEncoder(file)
err = encoder.Encode(user)
if err != nil {
file.Close()
return err
}
return file.Close()
}
func write(path string, user *User) {
err := writeToGob(path, user)
if err != nil {
log.Fatalf("writeToGob() failed with '%s'\n", err)
}
st, err := os.Stat(path)
if err != nil {
log.Fatalf("os.Stat() failed with '%s'\n", err)
}
fmt.Printf("Wrote user struct to file '%s' of size %d.\n", path, st.Size())
}
func read(path string) {
user := User{}
file, err := os.Open(path)
if err != nil {
log.Fatalf("os.Open('%s') failed with '%s'\n", path, err)
}
defer file.Close()
decoder := gob.NewDecoder(file)
err = decoder.Decode(&user)
if err != nil {
log.Fatalf("decoder.Decode() failed with '%s'\n", err)
}
fmt.Printf("\nRead from '%s' user:\n%#v\n", path, user)
}
func main() {
user := User{
Username: "Angus",
Password: "1234",
}
path := "user.gob"
write(path, &user)
read(path)
}
// :show end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment