simple auth example

This commit is contained in:
maddalax 2024-10-20 07:48:19 -05:00
parent 1d7ac301ab
commit 13f650b28b
5 changed files with 54 additions and 3 deletions

File diff suppressed because one or more lines are too long

View file

@ -81,3 +81,17 @@ function onUrlChange(newUrl: string) {
}
});
}
/*
400s should allow swapping by default, as it's useful to show error messages
*/
document.addEventListener('htmx:beforeSwap', function(evt) {
if(evt instanceof CustomEvent) {
// Allow 422 and 400 responses to swap
// We treat these as form validation errors
if (evt.detail.xhr.status === 422 || evt.detail.xhr.status === 400) {
evt.detail.shouldSwap = true;
evt.detail.isError = false;
}
}
});

View file

@ -12,8 +12,10 @@ htmx.defineExtension("mutation-error", {
}
const status = evt.detail.xhr.status;
if (status >= 400) {
htmx.findAll("[hx-on\\:\\:mutation-error]").forEach((element) => {
htmx.trigger(element, "htmx:mutation-error", { status });
document.querySelectorAll("*").forEach((element) => {
if (element.hasAttribute("hx-on::on-mutation-error")) {
htmx.trigger(element, "htmx:on-mutation-error", { status });
}
});
}
}

View file

@ -33,6 +33,22 @@ func GetRequestContext(r *http.Request) *RequestContext {
return r.Context().Value(RequestContextKey).(*RequestContext)
}
func (c *RequestContext) IsHttpPost() bool {
return c.Request.Method == http.MethodPost
}
func (c *RequestContext) IsHttpGet() bool {
return c.Request.Method == http.MethodGet
}
func (c *RequestContext) IsHttpPut() bool {
return c.Request.Method == http.MethodPut
}
func (c *RequestContext) IsHttpDelete() bool {
return c.Request.Method == http.MethodDelete
}
func (c *RequestContext) FormValue(key string) string {
return c.Request.FormValue(key)
}
@ -210,16 +226,27 @@ func (app *App) start() {
}
func writeHtml(w http.ResponseWriter, element Ren) error {
if element == nil {
return nil
}
w.Header().Set("Content-Type", "text/html")
_, err := fmt.Fprint(w, Render(element))
return err
}
func HtmlView(w http.ResponseWriter, page *Page) error {
// if the page is nil, do nothing, this can happen if custom response is written, such as a 302 redirect
if page == nil {
return nil
}
return writeHtml(w, page.Root)
}
func PartialViewWithHeaders(w http.ResponseWriter, headers *Headers, partial *Partial) error {
if partial == nil {
return nil
}
if partial.Headers != nil {
for s, a := range *partial.Headers {
w.Header().Set(s, a)
@ -236,6 +263,10 @@ func PartialViewWithHeaders(w http.ResponseWriter, headers *Headers, partial *Pa
}
func PartialView(w http.ResponseWriter, partial *Partial) error {
if partial == nil {
return nil
}
if partial.Headers != nil {
for s, a := range *partial.Headers {
w.Header().Set(s, a)

View file

@ -23,6 +23,10 @@ func NewPage(root Ren) *Page {
}
}
func EmptyPage() *Page {
return NewPage(Fragment())
}
func NewPageWithHttpMethod(httpMethod string, root *Element) *Page {
return &Page{
HttpMethod: httpMethod,