0

I'm writing a Go client to create backups via a REST-API. The REST-API Response with a multipart form data to a GET-Request. So the content of the response (type *http.Response) body looks like this:

--1ceb25134a5967272c26c9f3f543e7d26834a5967272c26c9f3f595caf08
Content-Disposition: form-data; name="configuration"; filename="test.gz"
Content-Type: application/x-gzip

...

--1ceb25134a5967272c26c9f3f543e7d26834a5967272c26c9f3f595caf08--

How can I extract the zip file from the response body?

I tried to use the builtin (net/http) methods but these requires an Request struct.

0

1 Answer 1

1

Use the mime/multipart package. Assuming that resp is the *http.Response, use the following code to iterate through the parts.

contentType := resp.Header.Get("Content-Type")
mediaType, params, err := mime.ParseMediaType(contentType)
if err != nil {
    log.Fatal(err)
}
if strings.HasPrefix(mediaType, "multipart/") {
    mr := multipart.NewReader(resp.Body, params["boundary"])
    for {
        p, err := mr.NextPart()
        if err == io.EOF {
            return
        }
        if err != nil {
            log.Fatal(err)
        }
        // p.FormName() is the name of the element.
        // p.FileName() is the name of the file (if it's a file)
        // p is an io.Reader on the part

        // The following code prints the part for demonstration purposes.
        slurp, err := ioutil.ReadAll(p)
        if err != nil {
            log.Fatal(err)
        }
        fmt.Printf("Part %q, %q: %q\n", p.FormName(), p.FileName(), slurp)
    }
}

The code in the answer handles errors by calling log.Fata. Adjust the error handling to meet the needs of your application.

Sign up to request clarification or add additional context in comments.

Comments

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.