1

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.

5
  • 1
    Check out mholt.github.io/curl-to-go (no affiliation, just something I've found useful before) Commented Apr 18, 2018 at 13:54
  • @Adrian yes, but this not convert me the complet curl command Commented Apr 18, 2018 at 13:55
  • What is missing? Commented Apr 18, 2018 at 13:57
  • --data-binary @build.bat Commented Apr 18, 2018 at 14:02
  • 1
    It's the same as --data. Go doesn't make a distinction between handling of binary and ASCII. Commented Apr 18, 2018 at 14:39

1 Answer 1

2

--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))
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much @Peter

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.