github.com/UlisseMini/utils@v0.0.0-20181216031219-f016c7ea9463/gobber/gobber.go (about)

     1  // Package gobber implements methods for easy saving of data to files.
     2  package gobber
     3  
     4  import (
     5  	"encoding/gob"
     6  	"os"
     7  )
     8  
     9  // Write writes a struct to a file
    10  func Write(filename string, thing interface{}) error {
    11  	file, err := os.OpenFile(
    12  		filename,
    13  		os.O_CREATE|os.O_WRONLY, 0666)
    14  	if err != nil {
    15  		return err
    16  	}
    17  	defer file.Close()
    18  
    19  	// if there was no error write the struct to the file
    20  	encoder := gob.NewEncoder(file)
    21  	err = encoder.Encode(thing)
    22  
    23  	// return possible error
    24  	return err
    25  
    26  }
    27  
    28  // Read reads a struct from a file
    29  func Read(filename string, thing interface{}) error {
    30  	file, err := os.Open(filename)
    31  	if err != nil {
    32  		return err
    33  	}
    34  	defer file.Close()
    35  
    36  	// if there was no error decode it
    37  	decoder := gob.NewDecoder(file)
    38  	err = decoder.Decode(thing)
    39  
    40  	// return possible error
    41  	return err
    42  }