英文:
Go http POST file
问题
我真的很新手Go语言,我需要在Go微服务中集成Zamzar。我需要POST
一个文件和一个数据类型(字符串)。
使用curl
的示例代码如下:
-u user:pass \
-X POST \
-F "source_file=@/tmp/portrait.gif" \
-F "target_format=png"
这是我目前的代码:
client := &http.Client{}
req, err := http.NewRequest("GET", "https://sandbox.zamzar.com/v1/jobs", nil)
req.SetBasicAuth("user", "pass")
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Error : %s", err)
} else {
fmt.Println(resp)
}
我如何将target_format
作为字符串发送,将source_file
作为文件发送?我已经有了文件([]byte
)。
英文:
I'm really new in Go and I have to integrate Zamzar in a Go microservice. I need to POST
a file and a data type (string).
Doing a curl
looks like this:
-u user:pass \
-X POST \
-F "source_file=@/tmp/portrait.gif" \
-F "target_format=png"
This is what I have so far:
client := &http.Client{}
req, err := http.NewRequest("GET", "https://sandbox.zamzar.com/v1/jobs", nil)
req.SetBasicAuth("user", "pass")
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Error : %s", err)
} else {
fmt.Println(resp)
}
How can I send the target_format
as a string and source_file
as a file? I already have the file ([]byte
)
1: https://developers.zamzar.com/docs
答案1
得分: 2
使用multipart.Writer来创建请求体:
var buf bytes.Buffer
mpw := multipart.NewWriter(&buf)
w, err := mpw.CreateFormFile("source_file", "portrait.gif")
if err != nil {
// 处理错误
}
if _, err := w.Write(imageBytes); err != nil {
// 处理错误
}
if err := mpw.WriteField("target_format", "png"); err != nil {
// 处理错误
}
if err := mpw.Close(); err != nil {
// 处理错误
}
req, err := http.NewRequest("GET", "https://sandbox.zamzar.com/v1/jobs", &buf)
req.Header.Set("Content-Type", mpw.FormDataContentType())
... 继续之前的操作。
英文:
Use multipart.Writer to create the request body:
var buf bytes.Buffer
mpw := multipart.NewWriter(&buf)
w, err := mpw.CreateFormFile("source_file", "portrait.gif")
if err != nil {
// handle error
}
if _, err := w.Write(imageBytes); err != nil {
// handle error
}
if err := mpw.WriteField("target_format", "png"); err != nil {
// handle error
}
if err := mpw.Close(); err != nil {
// handle error
}
req, err := http.NewRequest("GET", "https://sandbox.zamzar.com/v1/jobs", &buf)
req.Header.Set("Content-Type", mpw.FormDataContentType())
... continue as before.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论