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