This repository has been archived on 2021-08-10. You can view files and clone it, but cannot push or open issues or pull requests.
gtools/pb/proto.go

53 lines
1.2 KiB
Go

package pb
import (
"bytes"
"io/fs"
"io/ioutil"
"strconv"
"git.0cd.xyz/michael/request"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
)
// Read protocol buffer from file
func ReadFile(path string, message protoreflect.ProtoMessage) error {
file, err := ioutil.ReadFile(path)
if err != nil {
return err
}
if err := proto.Unmarshal(file, message); err != nil {
return err
}
return nil
}
// Write protocol buffer to file
func WriteFile(path string, message protoreflect.ProtoMessage, perm fs.FileMode) error {
msg, err := proto.Marshal(message)
if err != nil {
return err
}
if err := ioutil.WriteFile(path, msg, perm); err != nil {
return err
}
return nil
}
// SendFile protocol buffer to http address
func SendFile(url string, headers map[string]string, message protoreflect.ProtoMessage) (req *request.Response, err error) {
proto, err := proto.Marshal(message)
if err != nil {
return nil, err
}
buf := bytes.NewBuffer(proto)
headers["Content-Type"] = "application/x-protobuf"
headers["Content-Length"] = strconv.Itoa(buf.Len())
req, err = request.Post(url, headers, buf)
if err != nil {
return nil, err
}
return req, nil
}