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
Michael c64305953a send proto to url and basicauth support
Signed-off-by: Michael <michael.lindman@gmail.com>
2021-07-23 22:48:46 +01:00

72 lines
1.5 KiB
Go

package pb
import (
"bytes"
"io/fs"
"io/ioutil"
"mime/multipart"
"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 as multipart file to http address
func SendFile(filename, url string, headers map[string]string, message protoreflect.ProtoMessage) (req *request.Response, err error) {
body, err := proto.Marshal(message)
if err != nil {
return nil, err
}
buf := &bytes.Buffer{}
writer := multipart.NewWriter(buf)
part, err := writer.CreateFormFile("file", filename)
if err != nil {
return nil, err
}
part.Write(body)
for key, val := range map[string]string{
"type": "upload",
"synchronous": "true",
} {
writer.WriteField(key, val)
}
writer.Close()
headers["Content-Length"] = strconv.Itoa(buf.Len())
headers["Content-Type"] = writer.FormDataContentType()
req, err = request.Post(url,
headers, buf)
if err != nil {
return nil, err
}
return req, nil
}