diff --git a/README.md b/README.md index 2691bec..3b03b64 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,11 @@ including: webtools.SetContentType(w, webtools.ContentTypeRSS) ``` +- `Content-Disposition` +```go +webtools.SetAttachment(w, "note.txt") +``` + - `X-Robots-Tag` ```go diff --git a/headers.go b/headers.go index cba94fe..4048288 100644 --- a/headers.go +++ b/headers.go @@ -27,6 +27,14 @@ func SetContentType(w http.ResponseWriter, filetype MIMEType) { w.Header().Add("Content-Type", string(filetype)) } +// SetAttachment sets the Content-Disposition header on w to the given +// filename string. Use this in conjunction with SetContentType to create +// a downloadable file in an HTTP response. +func SetAttachment(w http.ResponseWriter, filename string) { + value := fmt.Sprintf("attachment; filename=%q", filename) + w.Header().Set("Content-Disposition", value) +} + // RobotIndex are correct sentinel values for indicating whether a page // should be indexed, as set in the X-Robots-Tag HTTP response header. // diff --git a/headers_test.go b/headers_test.go index 348472f..7aef8cb 100644 --- a/headers_test.go +++ b/headers_test.go @@ -26,6 +26,14 @@ func Test_SetContentType(t *testing.T) { must.Eq(t, "text/plain; charset=utf8", w.Header().Get("Content-Type")) } +func Test_SetAttachment(t *testing.T) { + t.Parallel() + + w := httptest.NewRecorder() + SetAttachment(w, "note.txt") + must.Eq(t, `attachment; filename="note.txt"`, w.Header().Get("Content-Disposition")) +} + func Test_SetBasicAuth(t *testing.T) { t.Parallel()