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

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

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵