hydra-webauthn/internal/route/common/helper.go

59 lines
1.4 KiB
Go

package common
import (
"net/http"
"strings"
"forge.cadoles.com/wpetit/hydra-webauthn/internal/config"
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/middleware/container"
"gitlab.com/wpetit/goweb/service"
"gitlab.com/wpetit/goweb/service/template"
"gitlab.com/wpetit/goweb/template/html"
)
func ExtendTemplateData(w http.ResponseWriter, r *http.Request, data template.Data) template.Data {
ctn := container.Must(r.Context())
data, err := template.Extend(data,
html.WithFlashes(w, r, ctn),
template.WithBuildInfo(w, r, ctn),
withBaseURL(w, r, ctn),
)
if err != nil {
panic(errors.Wrap(err, "could not extend template data"))
}
return data
}
func withBaseURL(w http.ResponseWriter, r *http.Request, ctn *service.Container) template.DataExtFunc {
return func(data template.Data) (template.Data, error) {
conf, err := config.From(ctn)
if err != nil {
return nil, errors.WithStack(err)
}
data["BaseURL"] = strings.TrimSuffix(conf.HTTP.BaseURL, "/")
return data, nil
}
}
func RenderErrorPage(w http.ResponseWriter, r *http.Request, statusCode int, title, description string) error {
ctn := container.Must(r.Context())
tmpl := template.Must(ctn)
data := ExtendTemplateData(w, r, template.Data{
"ErrorTitle": title,
"ErrorDescription": description,
})
w.WriteHeader(statusCode)
if err := tmpl.RenderPage(w, "error.html.tmpl", data); err != nil {
return errors.Wrap(err, "could not render error page")
}
return nil
}