-1

I just need to know an extremely simple way to send a file to a remote server using HTTP POST, in Go. I have already tried so many complicated methods with no luck. My curl command is this:

curl https://api.example.com/upload \
 --user api:YOUR_API_KEY \
 --data-binary @file.jpg \
 --dump-header apiresponse.txt

I would prefer something without using multipart. I would also prefer something which uses io.Reader, so that I can later implement a progress bar easily.

3
  • 2
    "I have already tried so many complicated methods with no luck" - can you show what you've tried and what issues you ran into?
    – Adrian
    Sep 19, 2018 at 13:30
  • 1
  • 1
    This was it. os.Open This was the missing simplicity that I was looking for. It worked.
    – Ameer
    Sep 19, 2018 at 15:33

1 Answer 1

5

Here is how I did it. Thanks to Peter for pointing out os.Open which was the missing piece for me.

func SendPostRequest(url string, filename string) (string, []byte) {
    api_key := ReadAPIKey("../.api_key")
    client := &http.Client{}
    data, err := os.Open(filename)
    if err != nil {
        log.Fatal(err)
    }
    req, err := http.NewRequest("POST", url, data)
    if err != nil {
        log.Fatal(err)
    }
    req.SetBasicAuth("api", api_key)
    resp, err := client.Do(req)
    if err != nil {
        log.Fatal(err)
    }
    content, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        log.Fatal(err)
    }
    return resp.Status, content
}

func main() {
    status, content := SendPostRequest("https://api.example.com/upload", "test.jpg")
    fmt.Println(status)
    fmt.Println(string(content))
}
2
  • 3
    Don't forget to Close() the file.
    – Peter
    Sep 19, 2018 at 16:37
  • Thanks for the tip. IMHO Go should have some kind of internal checking for un-closed file handles.
    – Ameer
    Sep 19, 2018 at 19:59

Not the answer you're looking for? Browse other questions tagged or ask your own question.