Add middleware for checking the requested mime type

This commit is contained in:
Melody Becker 2025-04-16 16:43:04 +02:00
parent 82ef7917ca
commit 087728cfe5
Signed by: mstar
SSH key fingerprint: SHA256:9VAo09aaVNTWKzPW7Hq2LW+ox9OdwmTSHRoD4mlz1yI

View file

@ -0,0 +1,36 @@
package webmiddleware
import (
"net/http"
"strings"
webutils "git.mstar.dev/mstar/goutils/http"
"git.mstar.dev/mstar/goutils/other"
)
func BuildMimetypeCheck(acceptedMimetypes []string) webutils.HandlerBuilder {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
acceptHeader := r.Header.Get("Accept")
for _, couldBe := range acceptedMimetypes {
if strings.Contains(acceptHeader, couldBe) {
h.ServeHTTP(w, r)
return
}
}
// Requested mimtype not in list of accepted ones, failing request with note
webutils.ProblemDetails(
w,
http.StatusUnsupportedMediaType,
"/errors/bad-accept-mime-type",
"unsupported mime type",
other.IntoPointer(
"The requested mime type is not supported. Please check extras for a list of supported mime types",
),
map[string]any{
"supported-mime-types": acceptedMimetypes,
},
)
})
}
}