diff --git a/lib/upload.go b/lib/upload.go index 4e210ce..a5fea54 100644 --- a/lib/upload.go +++ b/lib/upload.go @@ -43,3 +43,41 @@ func UploadExample(host string, token string, path string) (*http.Response, erro return RequestRaw(endpoint, mw.FormDataContentType(), body) } + +type ( + MultipartRequestOption func(writer *multipart.Writer) +) + +func MultipartRequest(endpoint string, options ...MultipartRequestOption) (*http.Response, error) { + body := &bytes.Buffer{} + w := multipart.NewWriter(body) + for _, opt := range options { + opt(w) + } + return RequestRaw(endpoint, w.FormDataContentType(), body) +} + +func SetMultipartField(field string, data []byte) MultipartRequestOption { + return func(writer *multipart.Writer) { + part, _ := writer.CreateFormField(field) + _, err := part.Write(data) + if err != nil { + zap.S().Panicf("CreatePart Failed") + } + } +} + +func SetMultipartFile(field string, path string) MultipartRequestOption { + return func(writer *multipart.Writer) { + filename := filepath.Base(path) + file, err := os.Open(path) + if err != nil { + zap.S().Panicf("Could not open '%s': %v", path, err) + } + part, _ := writer.CreateFormFile(field, filename) + _, err = io.Copy(part, file) + if err != nil { + zap.S().Panicf("CreatePart Failed") + } + } +}