66 lines
1.5 KiB
Go
66 lines
1.5 KiB
Go
package pb
|
|
|
|
import (
|
|
"bytes"
|
|
"io"
|
|
"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
|
|
}
|
|
|
|
// UnmarshalReader unmarshals io reader into proto message
|
|
func UnmarshalReader(r io.Reader, m protoreflect.ProtoMessage) error {
|
|
body, err := ioutil.ReadAll(r)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := proto.Unmarshal(body, m); err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|