Install the Datastar Go SDK
mainTo add the Datastar Go SDK to your Go project, use the go get command. This package requires Go 1.24 or later.
go get github.com/starfederation/datastar-gorepository·main·Indexed 41 days ago
https://github.com/starfederation/datastar-goA Go SDK for building interactive web applications using Datastar. It enables server-side control over the client-side DOM and state via Server-Sent Events (SSE), providing tools to read signals, patch elements, execute JavaScript, and manage redirects. Requires Go 1.24 or later.
To add the Datastar Go SDK to your Go project, use the go get command. This package requires Go 1.24 or later.
go get github.com/starfederation/datastar-goThe SDK allows you to interact with Datastar clients by reading signals from incoming requests and sending Server-Sent Events (SSE) to patch the DOM, update client-side state (signals), execute scripts, or redirect the browser.
Use datastar.ReadSignals(r, store) to decode signals sent from the client into a Go struct. The struct fields must have appropriate json tags.
Initialize an SSE writer using datastar.NewSSE(w, r). Once initialized, you can perform the following actions:
sse.PatchElements(html).sse.RemoveElement(selector).sse.MarshalAndPatchSignals(map[string]any).sse.ExecuteScript(script).sse.Redirect(url).import (
"net/http"
"github.com/starfederation/datastar-go/datastar"
)
// Define a struct to hold client signals
type Store struct {
Message string `json:"message"`
Count int `json:"count"`
}
func handler(w http.ResponseWriter, r *http.Request) {
// 1. Read signals from the request
store := &Store{}
if err := datastar.ReadSignals(r, store); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// 2. Create a Server-Sent Event writer
sse := datastar.NewSSE(w, r)
// 3. Perform actions
sse.PatchElements(`<div id="output">Hello from Datastar!</div>`)
sse.RemoveElement("#temporary-element")
sse.MarshalAndPatchSignals(map[string]any{
"message": "Updated message",
"count": store.Count + 1,
})
sse.ExecuteScript(`console.log("Hello from server!")`)
sse.Redirect("/new-page")
}