我是golang开发的新手,我想使用golang将文件上传到保管箱,这是我的curl命令:
curl -X POST https://content.dropboxapi.com/2/files/upload --header "Authorization: Bearer <token>" --header "Dropbox-API-Arg: {\"path\": \"/file_upload.txt\",\"mode\": \"add\",\"autorename\": true,\"mute\": false}" --header "Content-Type: application/octet-stream" --data-binary @build.bat
这是我的实际功能:
func uploadFile(filename string, token string){
jsonData := make(map[string]string)
jsonData["path"] = "/file_upload.txt"
jsonData["mode"] = "add"
jsonData["autorename"] = true
jsonData["mute"] = false
req, err := http.NewRequest("POST", "https://content.dropboxapi.com/2/files/upload", nil)
if err != nil {
// handle err
}
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Dropbox-Api-Arg", "{\"path\": \"/file_upload.txt\",\"mode\": \"add\",\"autorename\": true,\"mute\": false}")
req.Header.Set("Content-Type", "application/octet-stream")
resp, err := http.DefaultClient.Do(req)
if err != nil {
// handle err
}
defer resp.Body.Close()
}
问题是我不知道如何在我的go代码中添加--data-binary @ build.bat,以及如何在Dropbox-Api-Arg集中使用我的变量jsonData。
--data-binary @build.bat
说“将名为build.bat的文件的内容用作请求正文”。由于任何io.Reader都可以在Go中用作HTTP主体,因此* os.File实现了io.Reader,这很容易:
f, err := os.Open("build.bat")
defer f.Close()
req, err := http.NewRequest("POST", "https://content.dropboxapi.com/2/files/upload", f)
Dropbox-Api-Arg标头已经存在。大概其内容不是静态的,因此只需将其替换为地图的JSON编码即可:
jsonData := make(map[string]string)
jsonData["path"] = "/file_upload.txt"
jsonData["mode"] = "add"
jsonData["autorename"] = true
jsonData["mute"] = false
b, err := json.Marshal(jsonData)
req.Header.Set("Dropbox-Api-Arg", string(b))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句