...

Source file src/golang.conradwood.net/go-easyops/utils/proto.go

Documentation: golang.conradwood.net/go-easyops/utils

     1  package utils
     2  
     3  import (
     4  	"encoding/base64"
     5  
     6  	"github.com/golang/protobuf/proto"
     7  )
     8  
     9  func MarshalBytes(req proto.Message) ([]byte, error) {
    10  	data, err := proto.Marshal(req)
    11  	return data, err
    12  }
    13  func UnmarshalBytes(pdata []byte, req proto.Message) error {
    14  	err := proto.Unmarshal(pdata, req)
    15  	return err
    16  }
    17  
    18  // take a proto and convert it into a base64 string
    19  func Marshal(req proto.Message) (string, error) {
    20  	data, err := proto.Marshal(req)
    21  	if err != nil {
    22  		return "", err
    23  	}
    24  	b64 := base64.StdEncoding.EncodeToString(data)
    25  	return b64, nil
    26  }
    27  
    28  // take a base64 string and convert it into the proto
    29  func Unmarshal(b64string string, req proto.Message) error {
    30  	pdata, err := base64.StdEncoding.DecodeString(b64string)
    31  	if err != nil {
    32  		return err
    33  	}
    34  	err = proto.Unmarshal(pdata, req)
    35  	if err != nil {
    36  		return err
    37  	}
    38  
    39  	return nil
    40  }
    41  
    42  // write a proto to disk
    43  func WriteProto(filename string, req proto.Message) error {
    44  	data, err := proto.Marshal(req)
    45  	if err != nil {
    46  		return err
    47  	}
    48  	err = WriteFile(filename, data)
    49  	if err != nil {
    50  		return err
    51  	}
    52  	return nil
    53  }
    54  
    55  // read a proto from disk
    56  func ReadProto(filename string, req proto.Message) error {
    57  	b, err := ReadFile(filename)
    58  	if err != nil {
    59  		return err
    60  	}
    61  	err = UnmarshalBytes(b, req)
    62  	if err != nil {
    63  		return err
    64  	}
    65  	return nil
    66  }
    67  

View as plain text