feat(smalltrip,exceptions): headers field for additional headers to be sent with exception

This commit is contained in:
Guz
2025-02-25 16:00:21 -03:00
parent 5ff4f3a79b
commit 5c562eb363
2 changed files with 17 additions and 0 deletions

View File

@@ -18,6 +18,8 @@ type Exception struct {
// request context. Setting this field overrides any provided by the middleware
// and can be used to add a handler when using a middleware is not possible.
handler HandlerFunc `json:"-"`
headers http.Header
}
var (

View File

@@ -162,6 +162,13 @@ func HandlerTemplates(ts map[int]*template.Template, fallback HandlerFunc) Handl
func HandlerTemplate(t *template.Template, fallback HandlerFunc) HandlerFunc {
return func(e Exception, w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
for k := range e.headers {
w.Header().Set(k, e.headers.Get(k))
}
w.WriteHeader(e.Status)
err := t.Execute(w, e)
if err != nil {
e.Err = errors.Join(fmt.Errorf("executing Exception template: %s", e.Error()), e.Err)
@@ -183,6 +190,10 @@ func HandlerJSON(fallback HandlerFunc) HandlerFunc {
}
w.Header().Set("Content-Type", "application/json")
for k := range e.headers {
w.Header().Set(k, e.headers.Get(k))
}
w.WriteHeader(e.Status)
_, err = w.Write(j)
@@ -199,6 +210,10 @@ var _ HandlerFunc = HandlerJSON(HandlerText)
func HandlerText(e Exception, w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
for k := range e.headers {
w.Header().Set(k, e.headers.Get(k))
}
w.WriteHeader(e.Status)
_, err := w.Write([]byte(fmt.Sprintf(