19

Using go, how can I parse the Content-Disposition header retrieved from an http HEAD request to obtain the filename of the file?

Additionally, how do I retrieve the header itself from the http HEAD response? Is something like this correct?

resp, err := http.Head("http://example.com/")
//handle error
contentDisposition := resp.Header.Get("Content-Disposition")

The mime/multipart package specifies a method on the Part type that returns the filename (called FileName), but it's not clear to me how I should construct a Part, or from what.

1 Answer 1

35

You can parse the Content-Disposition header using the mime.ParseMediaType function.

disposition, params, err := mime.ParseMediaType(`attachment;filename="foo.png"`)
filename := params["filename"] // set to "foo.png"

This will also work for Unicode file names in the header (e.g. Content-Disposition: attachment;filename*="UTF-8''fo%c3%b6.png").

You can experiment with this here: http://play.golang.org/p/AjWbJB8vUk

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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