Home > Mobile >  Multipart upload to S3 with custom fields in golang
Multipart upload to S3 with custom fields in golang

Time:08-21

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 .

CodePudding user response:

I have used aws-sdk-for-go for interacting with S3. You can try that. Most APIs have examples so it is fairly quick to get your first version going. Check here - https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.CreateMultipartUpload.

CodePudding user response:

For programmers who switch from Python to Go, there is a wonderful library: https://github.com/levigross/grequests .

You can also choose for yourself the most convenient library from the list: https://github.com/avelino/awesome-go

  • Related