From c64305953a9793b4eb06a31bf0ed6b975d96f233 Mon Sep 17 00:00:00 2001 From: Michael Date: Fri, 23 Jul 2021 22:48:46 +0100 Subject: [PATCH] send proto to url and basicauth support Signed-off-by: Michael --- go.mod | 1 + nettools/net.go | 7 +++++++ pb/proto.go | 38 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 46 insertions(+) diff --git a/go.mod b/go.mod index 113ca3a..2a5eb6b 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module git.0cd.xyz/michael/gtools go 1.15 require ( + git.0cd.xyz/michael/request v0.0.6 github.com/OneOfOne/xxhash v1.2.8 github.com/gorilla/csrf v1.7.0 github.com/gorilla/mux v1.8.0 diff --git a/nettools/net.go b/nettools/net.go index 89dc53c..8546b79 100644 --- a/nettools/net.go +++ b/nettools/net.go @@ -1,6 +1,7 @@ package nettools import ( + "encoding/base64" "encoding/hex" "log" "math/big" @@ -8,6 +9,12 @@ import ( "net/http" ) +func BasicAuth(username, password string) map[string]string { + return map[string]string{ + "Authorization": "Basic " + base64.StdEncoding.EncodeToString([]byte(username+":"+password)), + } +} + // IP returns IP address from requester func IP(r *http.Request) (net.IP, error) { realip := r.Header.Get("x-forwarded-for") diff --git a/pb/proto.go b/pb/proto.go index d1760f6..5f2680d 100644 --- a/pb/proto.go +++ b/pb/proto.go @@ -1,9 +1,13 @@ 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" ) @@ -31,3 +35,37 @@ func WriteFile(path string, message protoreflect.ProtoMessage, perm fs.FileMode) } 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 +}