Commits

Ross Light committed d1498a3

Add common header constants and response functions

  • Participants
  • Parent commits 03e206a

Comments (0)

Files changed (1)

 	"encoding/json"
 	"fmt"
 	"net/http"
+	"strconv"
+	"strings"
+)
+
+// Common HTTP headers
+const (
+	HeaderAllow              = "Allow"
+	HeaderContentDisposition = "Content-Disposition"
+	HeaderContentEncoding    = "Content-Encoding"
+	HeaderContentLength      = "Content-Length"
+	HeaderContentType        = "Content-Type"
 )
 
 // Content types
 	JSONType = "application/json; charset=utf-8"
 )
 
+// MethodNotAllowed replies to a request with an HTTP 405 method not allowed error.
+func MethodNotAllowed(w http.ResponseWriter, methods ...string) {
+	w.Header().Set(HeaderAllow, strings.Join(methods, ", "))
+	http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+}
+
+// ContentLength sets the Content-Length header to size.
+func ContentLength(h http.Header, size int64) {
+	h.Set(HeaderContentLength, strconv.FormatInt(size, 10))
+}
+
+// Attachment sets the Content-Disposition header to an attachment with the given file name.
+func Attachment(h http.Header, base, ext string) {
+	h.Set(HeaderContentDisposition, "attachment; filename="+base+"."+ext)
+}
+
 // JSONResponse writes a JSON value to w, setting the Content-Type.
 func JSONResponse(w http.ResponseWriter, v interface{}) error {
 	w.Header().Set("Content-Type", JSONType)