Multipart upload to S3 with custom fields in golang

Viewed 45

I am new to golang , I have python code like below

import requests
url = "https://bucket.s3-us-east-1.amazonaws.com/"
data = { 'key': 'test.txt' }
files = { 'file': open('/tmp/test.txt', 'rb') }
r = requests.post(url, data=data, files=files)
print "status %s" % r.status_code

This works fine in python to upload a file , how do i do the same in GOlang , I tried something like below

package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "os"
)

func SendPostRequest(url string, filename string) (string, []byte) {
    client := &http.Client{}
    data, err := os.Open(filename)
    if err != nil {
        log.Fatal(err)
    }
    req, err := http.NewRequest("POST", url, data)
    req.Header.Set("Content-Type", "multipart/form-data")

    if err != nil {
        log.Fatal(err)
    }
    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://bucket.s3.amazonaws.com/", "what.html")
    fmt.Println(status)
    fmt.Println(string(content))
}

So I got following error from S3

The body of your POST request is not well-formed multipart/form-data.

P.s : I have given full access to my S3 bucket policy and I am trying to upload without any credentials.Later I will update this to work only with my VPC .

2 Answers
Related