### Install Datastar Go SDK Source: https://github.com/starfederation/datastar-go/blob/main/README.md Use this command to install the Datastar Go SDK. Requires Go 1.24 or later. ```bash go get github.com/starfederation/datastar-go ``` -------------------------------- ### Complete Example: Go HTTP Server with Datastar Signals Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/signals.md This example demonstrates how to use Datastar signals within a Go HTTP server. It shows reading signals from an incoming request, creating an SSE stream, and patching updated signal data back to the client. ```go package main import ( "fmt" "log" "net/http" "github.com/starfederation/datastar-go/datastar" ) type Store struct { Message string `json:"message"` Count int `json:"count"` } func handler(w http.ResponseWriter, r *http.Request) { // Read signals from the request store := &Store{} if err := datastar.ReadSignals(r, store); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } // Create SSE stream sse := datastar.NewSSE(w, r) // Patch signals to update client-side state newState := map[string]any{ "message": fmt.Sprintf("Processed: %s", store.Message), "count": store.Count + 1, } if err := sse.MarshalAndPatchSignals(newState); err != nil { log.Printf("Failed to patch signals: %v", err) } } func main() { http.HandleFunc("/api/action", handler) log.Fatal(http.ListenAndServe(":8080", nil)) } ``` -------------------------------- ### Complete Example: Execute Script, Dispatch Event, and Log Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/script-execution.md This example demonstrates a complete HTTP handler that uses Datastar-Go to execute a JavaScript snippet, dispatch a custom event with data, and log a message to the browser's console. It requires setting up an HTTP server and defining a handler function. ```go package main import ( "log" "net/http" "github.com/starfederation/datastar-go/datastar" ) func handler(w http.ResponseWriter, r *http.Request) { sse := datastar.NewSSE(w, r) // Log to browser console sse.ConsoleLog("Processing request...") // Execute custom JavaScript script := ` const items = document.querySelectorAll('.item'); items.forEach(item => item.classList.add('highlight')); ` if err := sse.ExecuteScript(script); err != nil { log.Printf("Script execution failed: %v", err) } // Dispatch custom event if err := sse.DispatchCustomEvent("dataProcessed", map[string]any{ "status": "success", "count": 42, }); err != nil { log.Printf("Event dispatch failed: %v", err) } } func main() { http.HandleFunc("/process", handler) log.Fatal(http.ListenAndServe(":8080", nil)) } ``` -------------------------------- ### Initialize SSE with Custom Context Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/sse.md Example of initializing a new SSE connection with a custom context. The context is created using context.WithValue. ```go ctx := context.WithValue(r.Context(), "user_id", 123) sse := datastar.NewSSE(w, r, datastar.WithContext(ctx)) ``` -------------------------------- ### ExecuteScript Go Example Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/script-execution.md Demonstrates executing simple and complex JavaScript code in the client browser using the ExecuteScript method. By default, scripts are removed after execution. ```go sse := datastar.NewSSE(w, r) // Execute simple JavaScript if err := sse.ExecuteScript(`console.log("Hello from server")`); err != nil { log.Printf("Failed to execute: %v", err) } // Execute more complex code script := ` { const count = parseInt(document.getElementById("count").textContent); document.getElementById("count").textContent = count + 1; } ` if err := sse.ExecuteScript(script); err != nil { log.Printf("Failed to execute: %v", err) } ``` -------------------------------- ### Client Signal via GET/DELETE URL Query Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/README.md Illustrates how clients can send signals to the server using a GET or DELETE request with the 'datastar' query parameter containing JSON data. ```http GET /api/action?datastar={"count":5} ``` -------------------------------- ### Initialize SSE with Compression Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/configuration.md Initializes a new SSE instance with a custom context and enables compression with server priority. Use this when you need fine-grained control over compression algorithms and levels. ```go package main import ( "context" "log" "net/http" "time" "github.com/starfederation/datastar-go/datastar" ) func handler(w http.ResponseWriter, r *http.Request) { // Initialize SSE with compression ctx := context.WithValue(r.Context(), "user_id", 123) sse := datastar.NewSSE(w, r, // Set custom context datastar.WithContext(ctx), // Enable compression with server priority datastar.WithCompression( datastar.WithBrotli( datastar.WithBrotliLevel(11), ), datastar.WithGzip( datastar.WithGzipLevel(gzip.BestCompression), ), datastar.WithServerPriority(), ), ) // Patch elements with full options sse.PatchElements( `
Updated
`, datastar.WithSelector("#container"), datastar.WithModeAppend(), datastar.WithPatchElementsEventID("patch-001"), datastar.WithViewTransitions(), ) // Patch signals with options sse.MarshalAndPatchSignals( map[string]any{ "count": 42, "status": "processing", }, datastar.WithPatchSignalsEventID("signals-001"), datastar.WithOnlyIfMissing(true), ) // Execute script with attributes sse.ExecuteScript( `console.log("Server sent this");`, datastar.WithExecuteScriptAutoRemove(true), datastar.WithExecuteScriptAttributeKVs("type", "module"), ) // Dispatch custom event sse.DispatchCustomEvent( "customEvent", map[string]any{ "detail": "some value", }, datastar.WithDispatchCustomEventSelector(".card"), datastar.WithDispatchCustomEventBubbles(true), ) } func main() { http.HandleFunc("/api/action", handler) log.Fatal(http.ListenAndServe(":8080", nil)) } ``` -------------------------------- ### Server-Sent Event: Patch Signals Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/README.md Example of a Server-Sent Event used to patch signals (data) on the client. It directly provides the JSON data to be updated. ```sse event: datastar-patch-signals signals {"count":6} ``` -------------------------------- ### Initialize SSE Stream with Options Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/configuration.md Configure the overall SSE stream by passing functional options to `NewSSE`. Options include setting a custom context or enabling message compression. ```go NewSSE(w, r, WithContext(ctxWithUser), WithCompression(WithBrotli(), WithGzip())) ``` -------------------------------- ### Send SSE Event with Custom ID Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/sse.md Example of sending an SSE event with a custom event ID. The ID is provided using the WithSSEEventId option. ```go sse.Send(eventType, dataLines, datastar.WithSSEEventId("event-123")) ``` -------------------------------- ### Enable Compression with Configurable Algorithms Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/compression.md Use `WithCompression` to enable compression on an SSE stream. Configure specific algorithms like Brotli and Gzip, and set the priority strategy. ```go sse := datastar.NewSSE( w, r, datastar.WithCompression( datastar.WithBrotli(), datastar.WithGzip(), datastar.WithServerPriority(), ), ) ``` -------------------------------- ### Get SSE connection context Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/sse.md Retrieves the context associated with the SSE connection. This context is derived from the request and is used to signal cancellation when the connection closes. ```go sse := datastar.NewSSE(w, r) cctx := sse.Context() select { case <-ctx.Done(): fmt.Println("Connection closed") } ``` -------------------------------- ### Enable Compression Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/README.md Initialize an SSE stream with compression enabled, supporting both Brotli and Gzip. This can reduce bandwidth usage. ```go sse := datastar.NewSSE(w, r, datastar.WithCompression( datastar.WithBrotli(), datastar.WithGzip(), ), ) ``` -------------------------------- ### Send SSE Event with Custom Retry Duration Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/sse.md Example of sending an SSE event with a custom retry duration. The duration is set using the WithSSERetryDuration option. ```go sse.Send(eventType, dataLines, datastar.WithSSERetryDuration(2*time.Second)) ``` -------------------------------- ### Server-Sent Event: Patch Elements Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/README.md Example of a Server-Sent Event used to patch HTML elements on the client. It specifies the target selector, mode, and the HTML content to be inserted. ```sse event: datastar-patch-elements selector #my-div mode append elements
new content
``` -------------------------------- ### Configure Compression Priority Strategy Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/configuration.md Define how the server selects a compression algorithm when both client and server support multiple. Options include client priority, server priority (default), or forcing a specific algorithm. ```go WithCompression( WithBrotli(), WithGzip(), WithClientPriority(), ) ``` -------------------------------- ### Configure Compression with CompressionOption Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/types.md Use CompressionOption for configuring compression. Used with WithCompression(). ```go type CompressionOption func(*compressionOptions) ``` -------------------------------- ### Reading Signals from an HTTP Request Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/signals.md Example of how to use the ReadSignals function to extract and unmarshal Datastar signals from an HTTP request into a Go struct. Ensure the struct fields have `json` tags. ```go import ( "net/http" "github.com/starfederation/datastar-go/datastar" ) type Store struct { Message string `json:"message"` Count int `json:"count"` } func handler(w http.ResponseWriter, r *http.Request) { store := &Store{} if err := datastar.ReadSignals(r, store); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } // store.Message and store.Count now contain values from the request fmt.Printf("Message: %s, Count: %d\n", store.Message, store.Count) } ``` -------------------------------- ### Initialize SSE Stream Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/README.md Create a new SSE stream to send updates to the client. This is the first step in establishing an SSE connection. ```go func handler(w http.ResponseWriter, r *http.Request) { sse := datastar.NewSSE(w, r) // Send updates... } ``` -------------------------------- ### Handle HTTP Requests and Send SSE with Datastar Go Source: https://github.com/starfederation/datastar-go/blob/main/README.md This Go code demonstrates how to read signals from an incoming HTTP request, create a Server-Sent Event (SSE) writer, and then use it to patch DOM elements, update client-side state, execute JavaScript, and redirect the browser. Ensure the `datastar` package is imported. ```go import ( "net/http" "github.com/starfederation/datastar-go/datastar" ) // Read signals from request type Store struct { Message string `json:"message"` Count int `json:"count"` } func handler(w http.ResponseWriter, r *http.Request) { // Read signals from the request store := &Store{} if err := datastar.ReadSignals(r, store); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } // Create a Server-Sent Event writer sse := datastar.NewSSE(w, r) // Patch elements in the DOM sse.PatchElements(`
Hello from Datastar!
`) // Remove elements from the DOM sse.RemoveElement("#temporary-element") // Patch signals (update client-side state) sse.MarshalAndPatchSignals(map[string]any{ "message": "Updated message", "count": store.Count + 1, }) // Execute JavaScript in the browser sse.ExecuteScript(`console.log("Hello from server!")`) // Redirect the browser sse.Redirect("/new-page") } ``` -------------------------------- ### Server-Sent Event: Patch Elements with Script Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/README.md Example of a Server-Sent Event used to patch HTML elements, specifically inserting a script tag. This demonstrates embedding executable code within the event. ```sse event: datastar-patch-elements elements ``` -------------------------------- ### Configure SSE Initialization with SSEOption Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/types.md Use SSEOption for configuring Server-Sent Event generator initialization. Used with NewSSE(). ```go type SSEOption func(*ServerSentEventGenerator) ``` -------------------------------- ### Basic Compression with Default Settings Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/compression.md Enables all supported compression algorithms with server-side priority. This is the simplest way to add compression to your SSE stream. ```go sse := datastar.NewSSE(w, r, datastar.WithCompression()) ``` -------------------------------- ### Configure Gzip Compression Level Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/compression.md Use `WithGzipLevel` to set the compression level for Gzip. Valid levels range from `gzip.NoCompression` (0) to `gzip.BestCompression` (9), with `gzip.DefaultCompression` (-1) offering a balance. ```go datastar.WithGzip(datastar.WithGzipLevel(gzip.BestCompression)) ``` -------------------------------- ### Run Datastar Go Tests Source: https://github.com/starfederation/datastar-go/blob/main/README.md Execute the test suite for the Datastar Go package using this command. ```bash go test ./... ``` -------------------------------- ### Configure Gzip Compression with GzipOption Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/types.md Use GzipOption for configuring Gzip compression parameters. ```go type GzipOption func(*gzip.Options) ``` -------------------------------- ### High-Level Convenience Methods Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/README.md These are the easiest methods to use and are suitable for most applications. ```APIDOC ## High-Level Convenience Methods Easiest to use, suitable for most applications: - `PatchElements(html, opts...) - `RemoveElement(selector) - `MarshalAndPatchSignals(data, opts...) - `ExecuteScript(code) - `ConsoleLog(msg)`, `Redirect(url)` ``` -------------------------------- ### WithBrotliLGWin Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/compression.md Configures the Brotli sliding window size for compression. ```APIDOC ## WithBrotliLGWin Configures the Brotli sliding window size. ### Signature ```go func WithBrotliLGWin(lgwin int) BrotliOption ``` ### Parameters #### Window Size (lgwin) - **lgwin** (int) - Required - Window size (10-24, or 0 for automatic). ### Example ```go datastar.WithBrotli(datastar.WithBrotliLGWin(22)) ``` ``` -------------------------------- ### Apply Functional Options Pattern in Go Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/INDEX.md Demonstrates the functional options pattern used in the SDK for configuring function calls. This pattern allows for flexible and readable API usage. ```go sse.PatchElements(html, datastar.WithSelector("#id"), datastar.WithModeAppend(), ) ``` -------------------------------- ### Configure Deflate Compression with DeflateOption Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/types.md Use DeflateOption for configuring Deflate compression parameters. ```go type DeflateOption func(*zlib.Options) ``` -------------------------------- ### Execute JavaScript and Redirect Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/README.md Execute arbitrary JavaScript code on the client or redirect the client to a new page. Also includes a convenience method for console logging. ```go sse.ExecuteScript(`console.log("Hello from server")`) sse.ConsoleLog("A message") sse.Redirect("/new-page") ``` -------------------------------- ### Client-Prioritized Compression Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/compression.md Enables multiple compression algorithms and respects the client's `Accept-Encoding` header. The SDK will use the algorithm preferred by the client. ```go sse := datastar.NewSSE( w, r, datastar.WithCompression( datastar.WithBrotli(), datastar.WithGzip(), datastar.WithZstd(), datastar.WithClientPriority(), // Use what the client prefers ), ) ``` -------------------------------- ### Custom Compression Strategy Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/compression.md Configures specific compression algorithms with custom levels and sets server priority. Use this to fine-tune compression for performance and compatibility. ```go sse := datastar.NewSSE( w, r, datastar.WithCompression( datastar.WithBrotli(datastar.WithBrotliLevel(11)), datastar.WithGzip(datastar.WithGzipLevel(gzip.BestCompression)), datastar.WithServerPriority(), // Prefer Brotli, fall back to Gzip ), ) ``` -------------------------------- ### Register Gzip Compression Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/compression.md Use `WithGzip` to register the Gzip compression algorithm. It accepts Gzip-specific options to configure the compression level. ```go datastar.WithCompression( datastar.WithGzip(datastar.WithGzipLevel(gzip.BestCompression)), ) ``` -------------------------------- ### Configure Gzip Compression Level Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/configuration.md Set the compression level for Gzip encoding. Use predefined constants like `gzip.BestCompression` for optimal compression. ```go WithGzip(WithGzipLevel(gzip.BestCompression)) ``` -------------------------------- ### Initialize and Update with Server-Sent Events Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/00-START-HERE.md This snippet demonstrates the common pattern for initializing a ServerSentEventGenerator and performing updates to DOM elements, state, and executing scripts. It utilizes functional options for configuration. ```go // Initialize sse := datastar.NewSSE(w, r, datastar.WithCompression(datastar.WithBrotli()), ) // Update DOM sse.PatchElements(html, datastar.WithSelector("#id")) // Update state sse.MarshalAndPatchSignals(map[string]any{"count": 42}) // Execute code sse.ExecuteScript(`alert("Hello!")`) ``` -------------------------------- ### Configure Brotli Compression with BrotliOption Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/types.md Use BrotliOption for configuring Brotli compression parameters. ```go type BrotliOption func(*brotli.Options) ``` -------------------------------- ### Configure Zstd Compression Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/configuration.md Use default Zstd compression settings by calling `WithZstd()` without any arguments. For advanced configuration, pass standard Zstd encoder options. ```go WithZstd() ``` -------------------------------- ### Compression Strategy Constants Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/compression.md Defines strategies for selecting compression algorithms. Use `ClientPriority` to respect the client's preference, `ServerPriority` for the server's first choice, or `Forced` to always use the first registered compressor. ```go type CompressionStrategy string const ( // ClientPriority: Use client's preferred compression if available ClientPriority CompressionStrategy = "client_priority" // ServerPriority: Use server's first available preferred compression ServerPriority CompressionStrategy = "server_priority" // Forced: Always use the first registered compressor Forced CompressionStrategy = "forced" ) ``` -------------------------------- ### Configure Individual SSE Events with SSEEventOption Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/types.md Use SSEEventOption for configuring individual Server-Sent Event data. Used with Send(). ```go type SSEEventOption func(*serverSentEventData) ``` -------------------------------- ### Configure Script Execution with ExecuteScriptOption Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/types.md Use ExecuteScriptOption for configuring script execution. Used with ExecuteScript() and related methods. ```go type ExecuteScriptOption func(*executeScriptOptions) ``` -------------------------------- ### Configure Compression Algorithms Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/configuration.md Register compression algorithms like Brotli, Zstd, Gzip, and Deflate for SSE streams. You can also specify a priority strategy for selecting the compression algorithm. ```go WithCompression( WithBrotli(opts...), WithZstd(opts...), WithGzip(opts...), WithDeflate(opts...), WithClientPriority(), ) ``` -------------------------------- ### Configure Signal Patches with PatchSignalsOption Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/types.md Use PatchSignalsOption for configuring signal patches. Used with PatchSignals() and MarshalAndPatchSignals(). ```go type PatchSignalsOption func(*patchSignalsOptions) ``` -------------------------------- ### Read-Patch-Respond Pattern Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/README.md A common pattern demonstrating the sequence of reading client signals, creating an SSE stream, patching DOM elements, and updating client signals. ```go func handler(w http.ResponseWriter, r *http.Request) { // 1. Read signals from request store := &Store{} datastar.ReadSignals(r, store) // 2. Create SSE stream sse := datastar.NewSSE(w, r) // 3. Patch DOM sse.PatchElements(`
updated
`, datastar.WithSelector("#content")) // 4. Update signals sse.MarshalAndPatchSignals(map[string]any{ "count": store.Count + 1, }) } ``` -------------------------------- ### Configure Deflate Compression Level Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/compression.md Use `WithDeflateLevel` to set the compression level for Deflate. Similar to Gzip, levels range from `zlib.NoCompression` (0) to `zlib.BestCompression` (9). ```go datastar.WithDeflateLevel(zlib.BestCompression) ``` -------------------------------- ### Configure Deflate Compression Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/configuration.md Customize Deflate compression by setting the compression level and providing an optional dictionary for repeated data. ```go WithDeflate( WithDeflateLevel(zlib.BestCompression), WithDeflateDictionary([]byte("common-prefix-data")), ) ``` -------------------------------- ### SSEOption Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/types.md Functional option for configuring SSE initialization. Used with NewSSE(). ```APIDOC ## SSEOption ### Description Functional option for configuring SSE initialization. Used with `NewSSE()`. ### Examples - `WithContext(ctx context.Context) SSEOption` — Set custom context - `WithCompression(opts ...CompressionOption) SSEOption` — Enable compression ``` -------------------------------- ### WithCompression Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/compression.md Enables compression on the SSE stream with configurable algorithms and strategies. It automatically selects a compression algorithm based on the strategy and the client's Accept-Encoding header. ```APIDOC ## WithCompression ### Description Enables compression on the SSE stream with configurable algorithms and strategies. It automatically selects a compression algorithm based on the strategy and the client's Accept-Encoding header. ### Function Signature ```go func WithCompression(opts ...CompressionOption) SSEOption ``` ### Parameters #### Variadic Options (`opts`) - **opts** (...CompressionOption) - Optional - Options to configure compression algorithms and strategy. ### Return Type - **SSEOption** — Returns an option to pass to `NewSSE`. ### Behavior When enabled, automatically selects a compression algorithm based on the strategy and client's `Accept-Encoding` header. If no compressors are explicitly configured, all supported algorithms (Brotli, Zstd, Gzip, Deflate) are registered with `ServerPriority`. ### Example ```go import "github.com/starfederation/datastar-go/datastar" // ... sse := datastar.NewSSE( w, r, datastar.WithCompression( datastar.WithBrotli(), datastar.WithGzip(), datastar.WithServerPriority(), ), ) ``` ``` -------------------------------- ### Execute Console Log Message Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/script-execution.md Use this to send a simple string message to the browser's console.log. Optional execution options can be provided. ```go sse := datastar.NewSSE(w, r) sse.ConsoleLog("Processing started") ``` -------------------------------- ### Create a new SSE stream Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/sse.md Initializes a new SSE stream on an HTTP response. Sets required HTTP headers, initializes the response controller, and flushes headers to begin the stream. The connection remains open until the request context is cancelled or the handler returns. ```go import ( "net/http" "github.com/starfederation/datastar-go/datastar" ) func handler(w http.ResponseWriter, r *http.Request) { sse := datastar.NewSSE(w, r) defer sse.Context().Done() // Send events via sse.PatchElements(), sse.PatchSignals(), etc. } ``` -------------------------------- ### WithBrotli Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/compression.md Registers the Brotli compression algorithm with optional configurations for level and window size. ```APIDOC ## WithBrotli Registers the Brotli compression algorithm. ### Signature ```go func WithBrotli(opts ...BrotliOption) CompressionOption ``` ### Parameters #### Options - **opts** (...BrotliOption) - Optional - Options to configure Brotli level and window size. ### Example ```go datastar.WithCompression( datastar.WithBrotli(datastar.WithBrotliLevel(6)), ) ``` ``` -------------------------------- ### Convenience Functions for View Transitions Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/elements.md Provides convenience functions to easily enable or disable view transitions for element patching. ```go datastar.WithViewTransitions() ``` ```go datastar.WithoutViewTransitions() ``` -------------------------------- ### Execute Formatted Console Log Message Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/script-execution.md Use this to send a formatted string message to the browser's console.log, similar to fmt.Sprintf. Arguments are optional. ```go itemID := 42 sse.ConsoleLogf("Processing item %d", itemID) ``` -------------------------------- ### Import Datastar Go SDK Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/README.md Import the Datastar Go SDK package to access its exported types and functions. This is the primary import path for all SDK functionalities. ```go import "github.com/starfederation/datastar-go/datastar" ``` -------------------------------- ### NewSSE Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/sse.md Creates and initializes a new SSE stream on an HTTP response. It sets up necessary headers and prepares the connection for event streaming. ```APIDOC ## NewSSE ### Description Creates and initializes a new SSE stream on an HTTP response. It sets up necessary headers and prepares the connection for event streaming. ### Method `NewSSE` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **w** (http.ResponseWriter) - Required - The HTTP response writer to stream events to - **r** (*http.Request) - Required - The HTTP request from the client - **opts** (...SSEOption) - Optional - Options to configure the SSE stream (e.g., compression, context) ### Return Type `*ServerSentEventGenerator` - A configured SSE generator ready to send events. ### Example ```go import ( "net/http" "github.com/starfederation/datastar-go/datastar" ) func handler(w http.ResponseWriter, r *http.Request) { sse := datastar.NewSSE(w, r) defer sse.Context().Done() // Send events via sse.PatchElements(), sse.PatchSignals(), etc. } ``` ``` -------------------------------- ### Configure Brotli Compression Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/configuration.md Adjust Brotli compression by specifying the compression level and the sliding window size. Higher levels and larger window sizes increase compression but also resource usage. ```go WithBrotli( WithBrotliLevel(11), WithBrotliLGWin(22), ) ``` -------------------------------- ### Compression Utilities Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/README.md Functions and options for configuring stream compression. ```APIDOC ## Compression Configuration ### Description Options for configuring different compression strategies for SSE streams. ### Functions - `WithCompression()` - `WithGzip()` - `WithDeflate()` - `WithBrotli()` - `WithZstd()` - `WithClientPriority()` - `WithServerPriority()` - `WithForced()` ``` -------------------------------- ### Format and Patch HTML Elements with Datastar Go Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/elements.md Use `PatchElementf` as a convenience wrapper for `PatchElements` that formats the HTML string using `fmt.Sprintf`. This is useful for dynamically generating HTML content. ```go itemID := 42 sse.PatchElementf(`
Item content
`, itemID) ``` -------------------------------- ### Navigation Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/MANIFEST.md Handles URL navigation within the application. ```APIDOC ## Redirect(), ReplaceURL() ### Description Handles navigation by redirecting to a new URL (`Redirect`) or replacing the current URL (`ReplaceURL`). ### Method (Assumed to be functions) ### Endpoint N/A (SDK functions) ### Parameters (Details not provided in source) ### Request Example ```go Redirect("/new-page") ReplaceURL("/current-page-replaced") ``` ### Response (Details not provided in source) ``` -------------------------------- ### Template Component Integration Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/README.md Patch Templ or GoStar components directly into the DOM. Specify the component and the target selector for patching. ```go sse.PatchElementTempl(MyComponent(data), datastar.WithSelectorID("result")) sse.PatchElementGostar(MyComponent(data), datastar.WithSelector(".card")) ``` -------------------------------- ### Set Client Priority Compression Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/compression.md Sets the compression strategy to ClientPriority. This strategy uses the client's preferred algorithm from the Accept-Encoding header if it's available. ```go datastar.WithCompression( datastar.WithBrotli(), datastar.WithGzip(), datastar.WithClientPriority(), // Use client's preferred algorithm ) ``` -------------------------------- ### WithBrotliLevel Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/compression.md Configures the Brotli compression level, affecting output size and CPU usage. ```APIDOC ## WithBrotliLevel Configures the Brotli compression level. ### Signature ```go func WithBrotliLevel(level int) BrotliOption ``` ### Parameters #### Level - **level** (int) - Required - Compression level (0-11, default 6). ### Behavior Higher levels produce smaller output but require more CPU. ### Example ```go datastar.WithBrotli(datastar.WithBrotliLevel(11)) // Maximum compression ``` ``` -------------------------------- ### GzipOption Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/types.md Option for configuring Gzip compression parameters. ```APIDOC ## GzipOption ### Description Option for configuring Gzip compression parameters. ### Examples - `WithGzipLevel(level int) GzipOption` — Set compression level ``` -------------------------------- ### Configure Brotli Compression Level Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/compression.md Configures the Brotli compression level. Higher levels result in smaller output but consume more CPU. Valid levels are 0-11. ```go datastar.WithBrotli(datastar.WithBrotliLevel(11)) // Maximum compression ``` -------------------------------- ### WithClientPriority Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/compression.md Sets the compression strategy to `ClientPriority`. The client's preferred compression algorithm (from `Accept-Encoding` header) is used if available. ```APIDOC ## WithClientPriority Sets the compression strategy to `ClientPriority`. The client's preferred compression algorithm (from `Accept-Encoding` header) is used if available. ```go func WithClientPriority() CompressionOption ``` **Example:** ```go datastar.WithCompression( datastar.WithBrotli(), datastar.WithGzip(), datastar.WithClientPriority(), // Use client's preferred algorithm ) ``` ``` -------------------------------- ### Configure Script Execution with Key-Value Attributes Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/script-execution.md Sets custom attributes on the script element using key-value pairs, providing a more convenient alternative to `WithExecuteScriptAttributes`. This option is used with the `ExecuteScript` function. ```go func WithExecuteScriptAttributeKVs(kvs ...string) ExecuteScriptOption ``` ```go sse.ExecuteScript( script, datastar.WithExecuteScriptAttributeKVs( "type", "module", "data-custom", "value", ), ) ``` -------------------------------- ### Register Deflate Compression Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/compression.md Use `WithDeflate` to register the Deflate compression algorithm. It accepts Deflate-specific options for level and dictionary. ```go datastar.WithCompression( datastar.WithDeflate(datastar.WithDeflateLevel(zlib.BestCompression)), ) ``` -------------------------------- ### Conditional Signal Patching Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/README.md Initialize signals only if they are missing on the client using `WithOnlyIfMissing(true)`. This prevents overwriting existing client-side data. ```go sse.MarshalAndPatchSignals( map[string]any{"userId": 123}, datastar.WithOnlyIfMissing(true), ) ``` -------------------------------- ### Set Server Priority Compression Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/compression.md Sets the compression strategy to ServerPriority, which is the default. The server's first registered compressor is used if the client supports it. ```go datastar.WithCompression( datastar.WithBrotli(), // Server prefers Brotli datastar.WithGzip(), // Fallback to Gzip datastar.WithServerPriority(), ) ``` -------------------------------- ### WithServerPriority Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/compression.md Sets the compression strategy to `ServerPriority` (default). The server's first registered compressor is used if the client supports it. ```APIDOC ## WithServerPriority Sets the compression strategy to `ServerPriority` (default). The server's first registered compressor is used if the client supports it. ```go func WithServerPriority() CompressionOption ``` **Example:** ```go datastar.WithCompression( datastar.WithBrotli(), // Server prefers Brotli datastar.WithGzip(), // Fallback to Gzip datastar.WithServerPriority(), ) ``` ``` -------------------------------- ### Convenience Functions for Element Patch Namespaces Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/elements.md Provides convenience functions for each namespace (HTML, SVG, MathML), simplifying the call to `WithNamespace`. ```go datastar.WithNamespaceHTML() ``` ```go datastar.WithNamespaceSVG() ``` ```go datastar.WithNamespaceMathML() ``` -------------------------------- ### Enable View Transitions for Element Patching Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/elements.md Enables the View Transition API when merging elements. This requires browser support and provides smooth visual transitions. ```go datastar.WithUseViewTransitions(true) ``` -------------------------------- ### WithDispatchCustomEventBubbles Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/script-execution.md Configures whether the event bubbles up the DOM (default: `true`). ```APIDOC ## WithDispatchCustomEventBubbles Configures whether the event bubbles up the DOM (default: `true`). ```go func WithDispatchCustomEventBubbles(bubbles bool) DispatchCustomEventOption ``` ``` -------------------------------- ### WithNamespace Convenience Functions Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/elements.md Convenience functions for each namespace (HTML, SVG, MathML), simplifying the process of setting the element namespace. ```APIDOC ## WithNamespace Convenience Functions ### Description Convenience functions for each namespace. ### Methods - func WithNamespaceHTML() PatchElementOption - func WithNamespaceSVG() PatchElementOption - func WithNamespaceMathML() PatchElementOption ``` -------------------------------- ### SSE Stream Initialization Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/MANIFEST.md Initializes a Server-Sent Events (SSE) stream. ```APIDOC ## NewSSE() ### Description Initializes a new Server-Sent Events (SSE) stream. ### Method (Assumed to be a constructor or factory function) ### Endpoint N/A (SDK function) ### Parameters (Details not provided in source) ### Request Example ```go sseStream := NewSSE() ``` ### Response - `ServerSentEventGenerator` (type) - The initialized SSE stream generator. ``` -------------------------------- ### Convenience Functions for Element Patch Modes Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/elements.md Provides convenience functions for each specific element patch mode, simplifying the call to `WithMode`. ```go sse.PatchElements(html, datastar.WithModeAppend()) ``` -------------------------------- ### ConsoleLogf Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/script-execution.md Executes `console.log()` in the browser with formatted output, similar to `fmt.Sprintf`. ```APIDOC ## ConsoleLogf ### Description Convenience method that executes `console.log()` with formatted output. ### Method Signature ```go func (sse *ServerSentEventGenerator) ConsoleLogf(format string, args ...any) error ``` ### Parameters #### Path Parameters - **format** (string) - Required - Format string (like `fmt.Sprintf`) - **args** (...any) - Optional - Arguments to format ### Return Type `error` — Returns an error if sending fails. ### Example ```go itemID := 42 sse.ConsoleLogf("Processing item %d", itemID) ``` ``` -------------------------------- ### Enable Message Compression for SSE Stream Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/sse.md Enables message compression on the SSE stream. Refer to the Compression section for more details on available compression options. ```go func WithCompression(opts ...CompressionOption) SSEOption ``` -------------------------------- ### CompressionOption Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/types.md Functional option for configuring compression. Used with WithCompression(). ```APIDOC ## CompressionOption ### Description Functional option for configuring compression. Used with `WithCompression()`. ### Examples - `WithGzip(opts ...GzipOption) CompressionOption` — Register Gzip compression - `WithBrotli(opts ...BrotliOption) CompressionOption` — Register Brotli compression - `WithClientPriority() CompressionOption` — Use client-preferred algorithm See [compression.md](api-reference/compression.md) for full list. ``` -------------------------------- ### Concurrent Console Logging with Goroutines Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/README.md Demonstrates thread-safe concurrent calls to ConsoleLog from multiple goroutines. This is safe due to internal mutex locking in ServerSentEventGenerator. ```go go sse.ConsoleLog("From goroutine 1") go sse.ConsoleLog("From goroutine 2") ``` -------------------------------- ### ExecuteScriptOption Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/script-execution.md Functional options for configuring script execution. ```APIDOC ## ExecuteScriptOption Functional option for configuring script execution. ```go type ExecuteScriptOption func(*executeScriptOptions) ``` ``` ```APIDOC ### WithExecuteScriptEventID Sets an event ID for the script execution event (used for SSE replay). ```go func WithExecuteScriptEventID(id string) ExecuteScriptOption ``` **Example:** ```go sse.ExecuteScript(script, datastar.WithExecuteScriptEventID("exec-123")) ``` ``` ```APIDOC ### WithExecuteScriptRetryDuration Sets the SSE retry duration for the script execution event. ```go func WithExecuteScriptRetryDuration(retryDuration time.Duration) ExecuteScriptOption ``` **Example:** ```go sse.ExecuteScript(script, datastar.WithExecuteScriptRetryDuration(2*time.Second)) ``` ``` ```APIDOC ### WithExecuteScriptAutoRemove Configures whether the script element is automatically removed after execution. ```go func WithExecuteScriptAutoRemove(autoremove bool) ExecuteScriptOption ``` **Example:** ```go // Keep the script element in the DOM after execution sse.ExecuteScript(script, datastar.WithExecuteScriptAutoRemove(false)) // Or use the default (remove after execution) sse.ExecuteScript(script, datastar.WithExecuteScriptAutoRemove(true)) ``` ``` ```APIDOC ### WithExecuteScriptAttributes Sets custom attributes on the script element (e.g., `type="module"`). ```go func WithExecuteScriptAttributes(attributes ...string) ExecuteScriptOption ``` **Parameters:** | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | attributes | ...string | Yes | — | Attributes in complete `key="value"` format | **Example:** ```go sse.ExecuteScript( script, datastar.WithExecuteScriptAttributes(`type="module"`, `defer`), ) ``` ``` ```APIDOC ### WithExecuteScriptAttributeKVs Sets custom attributes using key-value pairs (more convenient than `WithExecuteScriptAttributes`). ```go func WithExecuteScriptAttributeKVs(kvs ...string) ExecuteScriptOption ``` **Parameters:** Even parameters are keys, odd parameters are values. **Example:** ```go sse.ExecuteScript( script, datastar.WithExecuteScriptAttributeKVs( "type", "module", "data-custom", "value", ), ) ``` ``` -------------------------------- ### Patch Element with Templ Component Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/elements.md Renders a Templ component to HTML and sends it as an element patch. This method is a convenience adaptor and does not require Templ to be a direct dependency. Ensure the provided component implements the `Render` method. ```go // Assuming `MyComponent` is a Templ component component := MyComponent(data) if err := sse.PatchElementTempl(component, datastar.WithSelectorID("result")); err != nil { log.Printf("Failed to patch: %v", err) } ``` -------------------------------- ### Set Deflate Compression Dictionary Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/compression.md Use `WithDeflateDictionary` to provide a custom byte slice as a dictionary for Deflate compression, potentially improving compression ratios. ```go datastar.WithDeflateDictionary(dict []byte) ``` -------------------------------- ### Register Brotli Compression Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/compression.md Registers the Brotli compression algorithm with optional configurations. Use this to enable Brotli compression for data streams. ```go datastar.WithCompression( datastar.WithBrotli(datastar.WithBrotliLevel(6)), ) ``` -------------------------------- ### WithUseViewTransitions Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/elements.md Enables the View Transition API when merging elements. This provides smooth visual transitions for DOM updates, but requires browser support. ```APIDOC ## WithUseViewTransitions ### Description Enables the View Transition API when merging elements. ### Method func WithUseViewTransitions(useViewTransition bool) PatchElementOption ### Parameters #### Path Parameters - **useViewTransition** (bool) - Required - Whether to enable View Transitions. ### Request Example ```go datastar.WithUseViewTransitions(true) ``` ``` -------------------------------- ### Gzip Compression Configuration Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/compression.md Registers and configures the Gzip compression algorithm. You can specify options like compression level. ```APIDOC ## WithGzip Registers the Gzip compression algorithm. ### Signature ```go func WithGzip(opts ...GzipOption) CompressionOption ``` ### Parameters #### Path Parameters - **opts** (...GzipOption) - Optional - Options to configure Gzip level ### Request Example ```go datastar.WithCompression( datastar.WithGzip(datastar.WithGzipLevel(gzip.BestCompression)), ) ``` ``` ```APIDOC ## WithGzipLevel Configures the Gzip compression level. ### Signature ```go func WithGzipLevel(level int) GzipOption ``` ### Parameters #### Path Parameters - **level** (int) - Required - The compression level. Valid levels range from gzip.NoCompression (0) to gzip.BestCompression (9), with gzip.DefaultCompression (-1) being a common default. ### Request Example ```go datastar.WithGzip(datastar.WithGzipLevel(gzip.BestCompression)) ``` ``` -------------------------------- ### BrotliOption Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/types.md Option for configuring Brotli compression parameters. ```APIDOC ## BrotliOption ### Description Option for configuring Brotli compression parameters. ### Examples - `WithBrotliLevel(level int) BrotliOption` — Set compression level - `WithBrotliLGWin(lgwin int) BrotliOption` — Set sliding window size ``` -------------------------------- ### Configure Brotli Window Size Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/compression.md Configures the Brotli sliding window size. Valid values are 10-24, or 0 for automatic. Larger window sizes can improve compression ratios. ```go datastar.WithBrotli(datastar.WithBrotliLGWin(22)) ``` -------------------------------- ### Configure Element Patches with PatchElementOption Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/types.md Use PatchElementOption for configuring element patches. Used with PatchElements() and related methods. ```go type PatchElementOption func(*patchElementOptions) ``` -------------------------------- ### SSEEventOption Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/types.md Functional option for configuring individual SSE events. Used with Send(). ```APIDOC ## SSEEventOption ### Description Functional option for configuring individual SSE events. Used with `Send()`. ### Examples - `WithSSEEventId(id string) SSEEventOption` — Set event ID - `WithSSERetryDuration(retryDuration time.Duration) SSEEventOption` — Set retry duration ``` -------------------------------- ### View Transitions Convenience Functions Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/elements.md Convenience functions to easily enable or disable view transitions. ```APIDOC ## View Transitions Convenience Functions ### Description Convenience functions to enable or disable view transitions. ### Methods - func WithViewTransitions() PatchElementOption - func WithoutViewTransitions() PatchElementOption ``` -------------------------------- ### ConsoleLog Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/script-execution.md Executes `console.log()` in the browser to display a message. ```APIDOC ## ConsoleLog ### Description Convenience method that executes `console.log()` in the browser. ### Method Signature ```go func (sse *ServerSentEventGenerator) ConsoleLog(msg string, opts ...ExecuteScriptOption) error ``` ### Parameters #### Path Parameters - **msg** (string) - Required - Message to log to the browser console - **opts** (...ExecuteScriptOption) - Optional - Execution options ### Return Type `error` — Returns an error if sending fails. ### Example ```go sse := datastar.NewSSE(w, r) sse.ConsoleLog("Processing started") ``` ``` -------------------------------- ### Types and Enums Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/README.md Defines the core types, enums, and constants used throughout the SDK. ```APIDOC ## Core Types and Enums ### Description Enumerations and types used for configuring and operating the Datastar SDK. ### Types and Enums - `ElementPatchMode` (Outer, Inner, Remove, Append, Prepend, Before, After, Replace) - `Namespace` (HTML, SVG, MathML) - `EventType` (PatchElements, PatchSignals) - `CompressionStrategy` (ClientPriority, ServerPriority, Forced) ``` -------------------------------- ### Configure Patch Signals Only If Missing Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/signals.md Instructs the client to only patch signals that are currently missing on the client-side. This prevents overwriting existing signal values. ```go sse.MarshalAndPatchSignals( signals, datastar.WithOnlyIfMissing(true), ) ``` -------------------------------- ### Define SSE Initialization Option Type Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/sse.md Defines the functional option type for configuring SSE initialization. Use this to pass configuration to the SSE generator. ```go type SSEOption func(*ServerSentEventGenerator) ``` -------------------------------- ### Set Forced Compression Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/compression.md Sets the compression strategy to Forced. The first registered compressor is always used, regardless of client preferences. ```go datastar.WithCompression( datastar.WithBrotli(), datastar.WithForced(), // Always use Brotli ) ``` -------------------------------- ### WithCompression Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/sse.md Enables message compression on the SSE stream. This can reduce bandwidth usage for large data transfers. ```APIDOC ## WithCompression SSEOption ### Description Enables message compression on the SSE stream (see Compression section below). ### Method Signature ```go func WithCompression(opts ...CompressionOption) SSEOption ``` ### Parameters * **opts** (...CompressionOption) - Options for configuring message compression. ``` -------------------------------- ### Redirect Browser URL with Formatted URL Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/script-execution.md Convenience method that redirects with a formatted URL. Returns an error if sending fails. ```go userID := 42 sse.Redirectf("/users/%d/profile", userID) ``` -------------------------------- ### Error Handling for Patching Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/README.md Handle errors when patching DOM elements. Includes a check for `sse.IsClosed()` to avoid sending data over a closed connection. ```go if err := sse.PatchElements(html); err != nil { if sse.IsClosed() { return // Connection closed, no further sends needed } log.Printf("Failed to patch: %v", err) } ``` -------------------------------- ### WithMode Convenience Functions Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/elements.md Convenience functions for each specific patch mode, providing a more direct way to set the desired merge behavior. ```APIDOC ## WithMode Convenience Functions ### Description Convenience functions for each patch mode. ### Methods - func WithModeOuter() PatchElementOption - func WithModeInner() PatchElementOption - func WithModeRemove() PatchElementOption - func WithModePrepend() PatchElementOption - func WithModeAppend() PatchElementOption - func WithModeBefore() PatchElementOption - func WithModeAfter() PatchElementOption - func WithModeReplace() PatchElementOption ### Request Example ```go sse.PatchElements(html, datastar.WithModeAppend()) ``` ``` -------------------------------- ### Select Element by ID for Patching Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/elements.md A convenience wrapper to select an element directly by its ID. This is equivalent to using `WithSelector("#element-id")`. ```go datastar.WithSelectorID("my-element") ``` -------------------------------- ### Redirect Browser URL Source: https://github.com/starfederation/datastar-go/blob/main/_autodocs/api-reference/script-execution.md Redirects the browser to a different URL. Uses setTimeout() to ensure the redirect happens asynchronously. Returns an error if sending fails. ```go sse := datastar.NewSSE(w, r) if err := sse.Redirect("/dashboard"); err != nil { log.Printf("Failed to redirect: %v", err) } ```