Created
November 5, 2019 21:00
-
-
Save kjk/f6ceb3c30ebdc1e9eb8a695f328251d3 to your computer and use it in GitHub Desktop.
Encode data to file and decode from file
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
// :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