Skip to content

Commit

Permalink
WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
sakuhanight committed Mar 17, 2024
1 parent d8ee79a commit 7528f2b
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions lib/upload.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
}
}

0 comments on commit 7528f2b

Please sign in to comment.