MIME Type Regex for Go
/^(?:application|audio|font|image|model|multipart|text|video|message|x-[a-zA-Z0-9][a-zA-Z0-9!#$&\-^_]{0,30})/[a-zA-Z][a-zA-Z0-9!#$&\-^_.+]{0,100}(?:;\s*[a-zA-Z][a-zA-Z0-9\-]{0,30}=[^;\s]{1,50})*$/iWhat this pattern does
This page provides a comprehensive, battle-tested regular expression for matching mime type, ported and verified for Go. A rigorously tested regex reduces debugging time and protects your application from edge-case failures. The snippet below is ready to drop into your Go project — whether you're validating in a Gin handler, a gRPC service, or a command-line tool.
Go Implementation
// MIME Type
// ReDoS-safe | RegexVault — Web & Network > Misc
package validation
import "regexp"
var mimeTypeRe = regexp.MustCompile(`^(?:application|audio|font|image|model|multipart|text|video|message|x-[a-zA-Z0-9][a-zA-Z0-9!#$&\-^_]{0,30})/[a-zA-Z][a-zA-Z0-9!#$&\-^_.+]{0,100}(?:;\s*[a-zA-Z][a-zA-Z0-9\-]{0,30}=[^;\s]{1,50})*$`)
func ValidateMimeType(s string) bool {
return mimeTypeRe.MatchString(s)
}
// Example
// fmt.Println(ValidateMimeType("text/html")) // trueTest Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
text/html | html |
application/json | /json |
image/png | application/ |
audio/mpeg | text html |
text/html; charset=utf-8 | application\json |
application/vnd.ms-excel | bad-type/subtype |
x-custom/type | — |
When to use this pattern
This pattern is drawn from the Web & Network > Misc category and carries a ReDoS-safe certification. That matters for Go developers because Go's RE2 engine is inherently safe from catastrophic backtracking, but this pattern has been additionally verified for correctness. RegexVault audits patterns against known backtracking attack vectors, ensuring you have the necessary context before using this regex in a high-stakes production environment.
Common Pitfalls
MIME types are case-insensitive but should be normalized to lowercase for comparison. Never trust client-submitted Content-Type for security decisions — inspect file content directly.
Technical Notes
Top-level type is validated against IANA-defined values. x- prefix allows vendor/experimental types. Subtype may include vendor tree (vnd.), personal tree (prs.), or standard tree.
Have a pattern that belongs in the vault?
Submit it for review — community-verified patterns get credited to your GitHub handle. Free submissions join the queue. Priority review available for $15.
Submit a Pattern