Skip to content

Instantly share code, notes, and snippets.

@rjz
Last active October 31, 2023 06:55
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rjz/fe283b02cbaa50c5991e1ba921adf7c9 to your computer and use it in GitHub Desktop.
Save rjz/fe283b02cbaa50c5991e1ba921adf7c9 to your computer and use it in GitHub Desktop.
Validate golang http.Request content-type
import (
"mime"
"net/http"
"strings"
)
// Determine whether the request `content-type` includes a
// server-acceptable mime-type
//
// Failure should yield an HTTP 415 (`http.StatusUnsupportedMediaType`)
func HasContentType(r *http.Request, mimetype string) bool {
contentType := r.Header.Get("Content-type")
if contentType == "" {
return mimetype == "application/octet-stream"
}
for _, v := range strings.Split(contentType, ",") {
t, _, err := mime.ParseMediaType(v)
if err != nil {
break
}
if t == mimetype {
return true
}
}
return false
}
@alsritter
Copy link

Thank You

@BillZong
Copy link

Thanks for sharing this.
I'm curious about the charset types.
Should we consider it? The charset might be invalid.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment