Skip to content
Snippets Groups Projects
message.go 1.01 KiB
Newer Older
  • Learn to ignore specific revisions
  • 	"google.golang.org/protobuf/proto"
    
    	"io/ioutil"
    )
    
    /*
    Copycat source: https://dev.to/techschoolguru/go-generate-serialize-protobuf-message-4m7a
    
    Manuel Kieweg's avatar
    Manuel Kieweg committed
    */
    
    
    // Write writes protocol buffer message to binary file
    func Write(message proto.Message, filename string) error {
    	data, err := proto.Marshal(message)
    	if err != nil {
    		return fmt.Errorf("cannot marshal proto message to binary: %w", err)
    	}
    
    
    Manuel Kieweg's avatar
    Manuel Kieweg committed
    	err = ioutil.WriteFile(filename, data, 0600)
    
    	if err != nil {
    		return fmt.Errorf("cannot write binary data to file: %w", err)
    	}
    
    	return nil
    }
    
    
    // Read reads a binary file (containing a marshaled protocol buffer message)
    // and unmarshals it back into a protocol buffer message
    
    func Read(filename string, message proto.Message) error {
    	data, err := ioutil.ReadFile(filename)
    	if err != nil {
    		return fmt.Errorf("cannot read binary data from file: %w", err)
    	}
    	err = proto.Unmarshal(data, message)
    	if err != nil {
    		return fmt.Errorf("cannot unmarshal binary to proto message: %w", err)
    	}
    
    	return nil
    
    Manuel Kieweg's avatar
    Manuel Kieweg committed
    }