dongyou6909 2018-04-18 13:53
浏览 235
已采纳

将curl命令转换为golang函数

I'am new in golang developing, i want to upload file to dropbox using golang, this is my curl command :

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

this is my actual function :

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()
}

problem is i dont know how add --data-binary @build.bat in my go code, and how use my variable jsonData in Dropbox-Api-Arg set.

  • 写回答

1条回答 默认 最新

  • drexlz0623 2018-04-18 14:20
    关注

    --data-binary @build.bat says "Use the contents of the file named build.bat as the request body". Since any io.Reader works as an HTTP body in Go, and *os.File implements io.Reader that's easy enough:

    f, err := os.Open("build.bat")
    defer f.Close()
    req, err := http.NewRequest("POST", "https://content.dropboxapi.com/2/files/upload", f)
    

    The Dropbox-Api-Arg header is already there. Presumably its content isn't static, so just replace it with the JSON encoding of your map:

    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))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 有偿求qftp工具。能连接,下载文件,发送代码,windows环境,最好qt6 要qt creator写的
  • ¥70 刚刚看到一个人的网站居然是通过cname访问的
  • ¥15 Attributeerror:super object has no attribute '__sklearn_tags__'_'
  • ¥15 逆置单链表输出不完整
  • ¥15 宇视vms-B200-A16@R启动不了,如下图所示,在软件工具搜不到,如何解决?(操作系统-linux)
  • ¥500 寻找一名电子工程师完成pcb主板设计(拒绝AI生成式答案)
  • ¥15 关于#mysql#的问题:UNION ALL(相关搜索:sql语句)
  • ¥15 matlab二位可视化能否针对不同数值范围分开分级?
  • ¥15 已经创建了模拟器但是不能用来运行app 怎么办😭自己搞两天了
  • ¥15 关于#极限编程#的问题,请各位专家解答!