Quick actions

cmd+k|ctrl+k

Navigation

Languages

Essential Go / gob

Snippet info

Language

Go

Visibility

public

Author

kkowalczyk

Created

2019-09-19T17:15:32Z

Updated

2019-09-19T17:15:32Z

package main

import (
    "encoding/gob"
    "os"
    "log"
    "fmt"
)

type User struct {
    Username string
    Password string
}

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)
}
INFO