Last active
October 31, 2023 06:55
-
-
Save rjz/fe283b02cbaa50c5991e1ba921adf7c9 to your computer and use it in GitHub Desktop.
Validate golang http.Request content-type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
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
Thank You