From 069f55a1676bc306b37a2c4a5f461efb7b0c4ed1 Mon Sep 17 00:00:00 2001 From: Yurii Zinets Date: Wed, 24 Apr 2024 13:38:28 +0200 Subject: [PATCH] htmx.Post handler (experimental) --- htmx/post.go | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 htmx/post.go diff --git a/htmx/post.go b/htmx/post.go new file mode 100644 index 0000000..13161d9 --- /dev/null +++ b/htmx/post.go @@ -0,0 +1,26 @@ +package htmx + +import "go.kyoto.codes/v3/component" + +// Post is a helper function that simplifies the handling of stateful htmx POST requests. +func Post(ctx *component.Context, state component.State, handler func()) { + // We are only interested in POST requests here + if ctx.Request.Method == "POST" { + // Parse the form to get the state + ctx.Request.ParseForm() + // If no state is present in the form, we ignore. + // Porbably this is a regular POST request, not related to htmx. + if ctx.Request.FormValue("hx-state") == "" { + return + } + // If the state is disposable, we panic. + // This is a safety measure to prevent misuse of disposable components. + if ctx.Request.FormValue("hx-state") == "disposable" { + panic("incorrect use of disposable component") + } + // Unmarshal the state from the form + state.Unmarshal(state, ctx.Request.FormValue("hx-state")) + // Call the handler + handler() + } +}