Datastar Go SDK

repository·main·Indexed 41 days ago

https://github.com/starfederation/datastar-go

A 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.

Tokens
758
Snippets
2
Records
2
Agent score
3%

What's inside Datastar

  1. Use the Datastar Go SDK to manage DOM and signals

    main

    The 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.

    Reading Signals

    Use datastar.ReadSignals(r, store) to decode signals sent from the client into a Go struct. The struct fields must have appropriate json tags.

    Managing the Client via SSE

    Initialize an SSE writer using datastar.NewSSE(w, r). Once initialized, you can perform the following actions:

    • Patch Elements: Update specific DOM elements using sse.PatchElements(html).
    • Remove Elements: Delete elements from the DOM using sse.RemoveElement(selector).
    • Update Signals: Update client-side state using sse.MarshalAndPatchSignals(map[string]any).
    • Execute JavaScript: Run arbitrary JS in the browser using sse.ExecuteScript(script).
    • Redirect: Navigate the browser using 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")
    }