### Install datastar-go SDK
Source: https://pkg.go.dev/github.com/starfederation/datastar-go/%40v1.0
Installation command for the datastar-go SDK using go get. This is the standard way to add the package as a dependency to your Go project.
```go
go get github.com/starfederation/datastar-go
```
--------------------------------
### Datastar Go SDK Usage Example
Source: https://pkg.go.dev/github.com/starfederation/datastar-go/index
Demonstrates how to use the Datastar Go SDK within an HTTP handler. It shows reading signals, creating an SSE writer, patching/removing DOM elements, updating client-side state, executing JavaScript, and redirecting the browser. It depends on the 'net/http' package and the 'datastar' subpackage.
```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.RemoveElements("#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")
}
```
--------------------------------
### SSE Helper Functions
Source: https://pkg.go.dev/github.com/starfederation/datastar-go/%40v1.0.3/datastar_tab=versions
Provides functions to generate URL formats for SSE requests (GET, POST, PUT, Patch, Delete).
```APIDOC
## SSE Helper Functions
### Description
These functions construct URL formats for various Server-Sent Events (SSE) HTTP methods.
### Functions
* **GetSSE**(urlFormat string, args ...any) string
* Generates a URL for a GET request to an SSE endpoint.
* **PostSSE**(urlFormat string, args ...any) string
* Generates a URL for a POST request to an SSE endpoint.
* **PutSSE**(urlFormat string, args ...any) string
* Generates a URL for a PUT request to an SSE endpoint.
* **PatchSSE**(urlFormat string, args ...any) string
* Generates a URL for a PATCH request to an SSE endpoint.
* **DeleteSSE**(urlFormat string, args ...any) string
* Generates a URL for a DELETE request to an SSE endpoint.
```
--------------------------------
### Usage: Datastar Go SDK with HTTP Handler
Source: https://pkg.go.dev/github.com/starfederation/datastar-go/%40v1.0
Example Go code demonstrating how to use the datastar-go SDK within an HTTP handler. It shows reading signals from a request, creating a Server-Sent Event writer, patching and removing DOM elements, patching signals, executing JavaScript, and redirecting the browser.
```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.RemoveElements("#temporary-element")
// Patch signals (update client-side state)
sse.PatchSignals(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")
}
```
--------------------------------
### SSE HTTP Request Methods in Go
Source: https://pkg.go.dev/github.com/starfederation/datastar-go/datastar
This section outlines the functions available in the `datastar-go` package for making HTTP requests that are compatible with Server-Sent Events (SSE). It includes functions for deleting, getting, patching, posting, and putting SSE resources, utilizing URL formatting and variadic arguments for flexibility.
```go
package main
import "github.com/starfederation/datastar-go/sse"
func main() {
// Example: Getting SSE data from a specific URL format
url := "/api/v1/users/%s/events"
userID := "user123"
data := sse.GetSSE(url, userID)
// Example: Posting data to an SSE endpoint
postURL := "/api/v1/messages"
messageData := map[string]string{"text": "Hello"}
response := sse.PostSSE(postURL, messageData)
// Example: Deleting a resource via SSE
deleteURL := "/api/v1/items/%d"
itemID := 456
sse.DeleteSSE(deleteURL, itemID)
// Similar functions exist for PatchSSE and PutSSE
}
```
--------------------------------
### Create SSE HTTP Requests (Go)
Source: https://pkg.go.dev/github.com/starfederation/datastar-go/%40v1.0.2/datastar_tab=versions
Functions for creating Server-Sent Events (SSE) HTTP requests, including GET, POST, PUT, PATCH, and DELETE. These functions format URLs with provided arguments, returning a string representation of the request URL.
```go
func GetSSE(urlFormat string, args ...any) string
func PostSSE(urlFormat string, args ...any) string
func PutSSE(urlFormat string, args ...any) string
func PatchSSE(urlFormat string, args ...any) string
func DeleteSSE(urlFormat string, args ...any) string
```
--------------------------------
### SSE Initialization and Options
Source: https://pkg.go.dev/github.com/starfederation/datastar-go/%40v1.0.3/datastar
This section covers the initialization of Server-Sent Event streams and available configuration options.
```APIDOC
## NewSSE
### Description
Upgrades an http.ResponseWriter to an HTTP Server-Sent Event stream. The connection is kept alive until the context is canceled or the response is closed by returning from the handler. Run an event loop for persistent streaming.
### Method
`POST` (typically, but can be GET depending on context)
### Endpoint
`/sse` (example, actual endpoint depends on application)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```
// This is a server-side function, no client request body needed.
```
### Response
#### Success Response (101 Switching Protocols)
- **Upgrade** (string) - Indicates the protocol being switched to, e.g., `websocket`, `text/event-stream`.
- **Connection** (string) - Indicates that the connection should be upgraded, e.g., `Upgrade`.
#### Response Example
```
// No specific JSON response body for a successful upgrade.
// Client establishes a persistent connection.
```
## SSEOption Configuration Functions
### Description
These functions are used as options when creating a new SSE stream via `NewSSE` to configure its behavior.
### Functions
#### WithSSERetryDuration
##### Description
Overrides the `DefaultSseRetryDuration` for a single server-sent event.
##### Parameters
- **retryDuration** (`time.Duration`) - Required - The duration to wait before retrying.
#### WithCompression
##### Description
Adds compression to the server-sent event stream.
##### Parameters
- **opts** (`...CompressionOption`) - Optional - Compression-specific options.
#### WithContext
##### Description
Allows setting a new, more specific context. Must always be a context derived from the request context (not enforced). Useful for setting values to be read by template components.
##### Parameters
- **ctx** (`context.Context`) - Required - The context to associate with the SSE stream.
```
--------------------------------
### Generate SSE HTTP Get Attribute (Go)
Source: https://pkg.go.dev/github.com/starfederation/datastar-go/%40v1.0.3/datastar
The `GetSSE` function generates the `hx-get` HTML attribute, simplifying the creation of GET requests within Datastar. It accepts a URL format and variadic arguments to build the attribute string.
```Go
func GetSSE(urlFormat string, args ...any) string
// GetSSE is a convenience method for generating Datastar backend get action attribute.
```
--------------------------------
### Get Context (Go)
Source: https://pkg.go.dev/github.com/starfederation/datastar-go/%40v1.0.0/datastar_tab=versions
Retrieves the context associated with the Server-Sent Event generator. This context can be used for managing request-scoped values, cancellation signals, and deadlines.
```Go
func (sse *ServerSentEventGenerator) Context() context.Context
```
--------------------------------
### Compression Options
Source: https://pkg.go.dev/github.com/starfederation/datastar-go/%40v1.0.1/datastar_tab=versions
Configuration options for various compression algorithms like Gzip, Brotli, and Deflate, including level and dictionary settings.
```APIDOC
## Compression Options
### Description
Configuration options for various compression algorithms supported by the library.
### Compression Strategy
* **type CompressionStrategy string**
* **const ClientPriority**
* **const ServerPriority**
* **const Forced**
### Compression Options
* **type CompressionOption func(*compressionOptions)**
* **WithClientPriority() CompressionOption**
* Description: Enables client priority for compression.
* Returns:
* CompressionOption - A compression option.
* **WithServerPriority() CompressionOption**
* Description: Enables server priority for compression.
* Returns:
* CompressionOption - A compression option.
* **WithForced() CompressionOption**
* Description: Forces compression.
* Returns:
* CompressionOption - A compression option.
* **WithGzip(opts ...GzipOption) CompressionOption**
* Description: Configures Gzip compression.
* Parameters:
* opts (...GzipOption) - Gzip specific options.
* Returns:
* CompressionOption - A compression option.
* **WithBrotli(opts ...BrotliOption) CompressionOption**
* Description: Configures Brotli compression.
* Parameters:
* opts (...BrotliOption) - Brotli specific options.
* Returns:
* CompressionOption - A compression option.
* **WithDeflate(opts ...DeflateOption) CompressionOption**
* Description: Configures Deflate compression.
* Parameters:
* opts (...DeflateOption) - Deflate specific options.
* Returns:
* CompressionOption - A compression option.
* **WithZstd(opts ...zstd_opts.EOption) CompressionOption**
* Description: Configures Zstandard compression.
* Parameters:
* opts (...zstd_opts.EOption) - Zstandard specific options.
* Returns:
* CompressionOption - A compression option.
### Gzip Options
* **type GzipOption func(*gzip.Options)**
* **WithGzipLevel(level int) GzipOption**
* Description: Sets the Gzip compression level.
* Parameters:
* level (int) - The compression level.
* Returns:
* GzipOption - A Gzip option.
### Brotli Options
* **type BrotliOption func(*brotli.Options)**
* **WithBrotliLevel(level int) BrotliOption**
* Description: Sets the Brotli compression level.
* Parameters:
* level (int) - The compression level.
* Returns:
* BrotliOption - A Brotli option.
* **WithBrotliLGWin(lgwin int) BrotliOption**
* Description: Sets the Brotli LGWin parameter.
* Parameters:
* lgwin (int) - The LGWin value.
* Returns:
* BrotliOption - A Brotli option.
### Deflate Options
* **type DeflateOption func(*zlib.Options)**
* **WithDeflateLevel(level int) DeflateOption**
* Description: Sets the Deflate compression level.
* Parameters:
* level (int) - The compression level.
* Returns:
* DeflateOption - A Deflate option.
* **WithDeflateDictionary(dict []byte) DeflateOption**
* Description: Sets a dictionary for Deflate compression.
* Parameters:
* dict ([]byte) - The dictionary data.
* Returns:
* DeflateOption - A Deflate option.
```
--------------------------------
### Prefetching and Redirection
Source: https://pkg.go.dev/github.com/starfederation/datastar-go/%40v1.0.2/datastar
Utilities for prefetching resources and performing client-side redirections using Server-Sent Events.
```APIDOC
## Prefetch URLs
### Description
Initiates prefetching of specified URLs on the client-side.
### Method
N/A (This is a method call on `ServerSentEventGenerator`)
### Endpoint
N/A
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
- **urls** (...string) - A list of URLs to prefetch.
### Request Example
```go
var sseGenerator ServerSentEventGenerator
sseGenerator.Prefetch("/resource1.js", "/resource2.css")
```
### Response
#### Success Response (200)
Returns `nil` on success.
#### Response Example
```
nil
```
## Redirect Client
### Description
Triggers a client-side redirect to a specified URL. Options can be provided to control the redirection behavior.
### Method
N/A (This is a method call on `ServerSentEventGenerator`)
### Endpoint
N/A
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
- **url** (string) - The URL to redirect to.
- **opts** (...ExecuteScriptOption) - Options for executing the redirect script.
### Request Example
```go
var sseGenerator ServerSentEventGenerator
sseGenerator.Redirect("/dashboard")
```
### Response
#### Success Response (200)
Returns `nil` on success.
#### Response Example
```
nil
```
## Redirect with Formatted URL
### Description
Triggers a client-side redirect using a formatted URL string.
### Method
N/A (This is a method call on `ServerSentEventGenerator`)
### Endpoint
N/A
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
- **format** (string) - The format string for the URL.
- **args** (...any) - Arguments to format the URL.
### Request Example
```go
var sseGenerator ServerSentEventGenerator
sseGenerator.Redirectf("/users/%d", 123)
```
### Response
#### Success Response (200)
Returns `nil` on success.
#### Response Example
```
nil
```
```
--------------------------------
### Get Associated SSE Context
Source: https://pkg.go.dev/github.com/starfederation/datastar-go/%40v1.0.3/datastar
Returns the context associated with the upgraded Server-Sent Event connection. This is equivalent to calling `request.Context()`.
```go
func (sse *ServerSentEventGenerator) Context() context.Context {
// ... implementation details ...
}
```
--------------------------------
### SSE Options
Source: https://pkg.go.dev/github.com/starfederation/datastar-go/datastar
Top-level options for configuring the SSE stream, including compression and context.
```APIDOC
## SSE Options
Top-level options for configuring the Server-Sent Events stream.
### SSEOption
* **Description**: Options for the SSE stream.
* **WithCompression**
* **Description**: Configures compression for the SSE stream.
* **Method**: `func WithCompression(opts ...CompressionOption) SSEOption`
* **Parameters**: `opts` (...CompressionOption) - Compression configuration options.
* **WithContext**
* **Description**: Sets the context for the SSE stream.
* **Method**: `func WithContext(ctx context.Context) SSEOption`
* **Parameters**: `ctx` (context.Context) - The context to use.
```
--------------------------------
### Get SSE Connection Context in Go
Source: https://pkg.go.dev/github.com/starfederation/datastar-go/%40v1.0.1/datastar
Context returns the context associated with the Server-Sent Event connection. This allows access to request-specific context information, similar to calling request.Context.
```go
func (sse *ServerSentEventGenerator) Context() context.Context
```
--------------------------------
### Get SSE Connection Context
Source: https://pkg.go.dev/github.com/starfederation/datastar-go/%40v1.0.2/datastar
Returns the context associated with the upgraded SSE connection. This is equivalent to calling `request.Context()` and provides access to the request's context.
```go
func (sse *ServerSentEventGenerator) Context() context.Context {
// Implementation details would go here
}
```
--------------------------------
### Context and Prefetching
Source: https://pkg.go.dev/github.com/starfederation/datastar-go/%40v1.0.1/datastar_tab=versions
Provides access to the context associated with the SSE generator and allows prefetching resources by specifying a list of URLs.
```go
func (sse *ServerSentEventGenerator) Context() context.Context
func (sse *ServerSentEventGenerator) Prefetch(urls ...string) error
```
--------------------------------
### Define SSE Option Configuration Functions in Go
Source: https://pkg.go.dev/github.com/starfederation/datastar-go/%40v1.0.0/datastar
SSEOption is a function type used to configure ServerSentEventGenerator during initialization. WithCompression is an example that accepts CompressionOption variadic arguments to enable compression for the SSE stream.
```go
type SSEOption func(*ServerSentEventGenerator)
func WithCompression(opts ...CompressionOption) SSEOption
```
--------------------------------
### Manage SSE Connections and Data - Go
Source: https://pkg.go.dev/github.com/starfederation/datastar-go/datastar_tab=versions
Includes methods for managing the SSE connection context, prefetching resources, redirecting the client, and sending structured SSE events. Supports different ways to send data, including formatted strings and byte slices.
```Go
func (sse *ServerSentEventGenerator) Context() context.Context
```
```Go
func (sse *ServerSentEventGenerator) Prefetch(urls ...string) error
```
```Go
func (sse *ServerSentEventGenerator) Redirect(url string, opts ...ExecuteScriptOption) error
```
```Go
func (sse *ServerSentEventGenerator) Redirectf(format string, args ...any) error
```
```Go
func (sse *ServerSentEventGenerator) ReplaceURL(u url.URL, opts ...ExecuteScriptOption) error
```
```Go
func (sse *ServerSentEventGenerator) ReplaceURLQuerystring(r *http.Request, values url.Values, opts ...ExecuteScriptOption) error
```
```Go
func (sse *ServerSentEventGenerator) Send(eventType EventType, dataLines []string, opts ...SSEEventOption) error
```
--------------------------------
### Create Server-Sent Event Generator (Go)
Source: https://pkg.go.dev/github.com/starfederation/datastar-go/%40v1.0.0/datastar_tab=versions
Initializes a new ServerSentEventGenerator. It requires an http.ResponseWriter and *http.Request, and accepts optional SSEOptions for configuration. This is the entry point for utilizing SSE functionalities.
```Go
func NewSSE(w http.ResponseWriter, r *http.Request, opts ...SSEOption) *ServerSentEventGenerator
```
--------------------------------
### HTTP Request Functions
Source: https://pkg.go.dev/github.com/starfederation/datastar-go/datastar
This section covers utility functions for making HTTP requests using different methods like GET, POST, PUT, PATCH, and DELETE. These functions are designed to work with SSE.
```APIDOC
## HTTP Request Functions
These functions facilitate making various HTTP requests, commonly used in conjunction with SSE functionalities.
### DeleteSSE
* **Description**: Sends a DELETE request.
* **Method**: `func DeleteSSE(urlFormat string, args ...any) string`
* **Parameters**:
* `urlFormat` (string) - The URL format string.
* `args` (...any) - Arguments for the URL format string.
* **Returns**: `string` - The response from the DELETE request.
### GetSSE
* **Description**: Sends a GET request.
* **Method**: `func GetSSE(urlFormat string, args ...any) string`
* **Parameters**:
* `urlFormat` (string) - The URL format string.
* `args` (...any) - Arguments for the URL format string.
* **Returns**: `string` - The response from the GET request.
### PatchSSE
* **Description**: Sends a PATCH request.
* **Method**: `func PatchSSE(urlFormat string, args ...any) string`
* **Parameters**:
* `urlFormat` (string) - The URL format string.
* `args` (...any) - Arguments for the URL format string.
* **Returns**: `string` - The response from the PATCH request.
### PostSSE
* **Description**: Sends a POST request.
* **Method**: `func PostSSE(urlFormat string, args ...any) string`
* **Parameters**:
* `urlFormat` (string) - The URL format string.
* `args` (...any) - Arguments for the URL format string.
* **Returns**: `string` - The response from the POST request.
### PutSSE
* **Description**: Sends a PUT request.
* **Method**: `func PutSSE(urlFormat string, args ...any) string`
* **Parameters**:
* `urlFormat` (string) - The URL format string.
* `args` (...any) - Arguments for the URL format string.
* **Returns**: `string` - The response from the PUT request.
```
--------------------------------
### Compression Options
Source: https://pkg.go.dev/github.com/starfederation/datastar-go/%40v1.0.2/datastar
Configures compression algorithms like Brotli, Deflate, and Gzip for Server-Sent Events.
```APIDOC
## Compression Options
### Description
Options for configuring different compression algorithms used with Server-Sent Events.
### Types
- **CompressionOption**: Interface for compression configurations.
- **BrotliOption**: Options for Brotli compression.
- **DeflateOption**: Options for Deflate compression.
- **GzipOption**: Options for Gzip compression.
### Functions
#### Brotli Options
- `func WithBrotliLGWin(lgwin int) BrotliOption`: Sets the LZ77 window size for Brotli.
- `func WithBrotliLevel(level int) BrotliOption`: Sets the compression level for Brotli.
#### Deflate Options
- `func WithDeflateDictionary(dict []byte) DeflateOption`: Sets a dictionary for Deflate compression.
- `func WithDeflateLevel(level int) DeflateOption`: Sets the compression level for Deflate.
#### Gzip Options
- `func WithGzipLevel(level int) GzipOption`: Sets the compression level for Gzip.
#### General Compression Options
- `func WithBrotli(opts ...BrotliOption) CompressionOption`: Enables Brotli compression with specified options.
- `func WithClientPriority() CompressionOption`: Indicates client preference for compression.
- `func WithDeflate(opts ...DeflateOption) CompressionOption`: Enables Deflate compression with specified options.
- `func WithForced() CompressionOption`: Forces compression.
- `func WithGzip(opts ...GzipOption) CompressionOption`: Enables Gzip compression with specified options.
- `func WithServerPriority() CompressionOption`: Indicates server preference for compression.
- `func WithZstd(opts ...zstd_opts.EOption) CompressionOption`: Enables Zstandard compression with specified options.
### Usage
These options are passed to `NewSSE` via the `SSEOption` interface, specifically using `WithCompression`.
### Request Example
```go
// Example: Using Brotli compression
// opts := []SSEOption{WithCompression(WithBrotli(WithBrotliLevel(5), WithBrotliLGWin(22)))}
// sse := NewSSE(w, r, opts...)
// Example: Using Gzip compression
// opts := []SSEOption{WithCompression(WithGzip(WithGzipLevel(9)))}
// sse := NewSSE(w, r, opts...)
```
### Response
#### Success Response (200)
Configuration applied to the SSE stream.
#### Response Example
```json
{
"example": "SSE stream configured with specified compression."
}
```
```
--------------------------------
### Read Datastar Signals from HTTP Request (Go)
Source: https://pkg.go.dev/github.com/starfederation/datastar-go/%40v1.0.1/datastar
This function reads Datastar signals from an incoming HTTP request. It handles extracting signals from URL query parameters for GET requests or the request body (as JSON) for other methods.
```go
func ReadSignals(r *http.Request, signals any) error {
// Expects signals in [URL.Query] for http.MethodGet requests. Expects JSON-encoded signals in [Request.Body] for other request methods.
// ... implementation omitted ...
}
```
--------------------------------
### Compression Options
Source: https://pkg.go.dev/github.com/starfederation/datastar-go/%40v1.0.0/datastar
Configuration options for compressing Server-Sent Events using Brotli.
```APIDOC
## Compression Options
### Description
This section describes the options available for compressing Server-Sent Events (SSE) messages, primarily focusing on Brotli compression.
### Types
- `BrotliOption`: A function type used to configure Brotli compression settings.
- `CompressionOption`: A function type used to configure general SSE message compression.
### Functions
- `WithBrotli(opts ...BrotliOption) CompressionOption`: Appends a Brotli compressor to the list of compressors used for SSE messages. Accepts `BrotliOption` arguments to further configure Brotli.
- `WithBrotliLGWin(lgwin int) BrotliOption`: Sets the sliding window size for Brotli compression. Valid values are between 10 and 24. Defaults to 0 for automatic selection.
- `WithBrotliLevel(level int) BrotliOption`: Sets the compression level for Brotli. Levels range from 0 (fastest) to 11 (best compression). Defaults to 6.
```
--------------------------------
### Server-Sent Events (SSE) Functions
Source: https://pkg.go.dev/github.com/starfederation/datastar-go/%40v1.0.0/datastar_tab=versions
This section details the functions for managing Server-Sent Events (SSE), including methods for deleting, getting, patching, and posting SSE data. It also covers options for configuring SSE requests.
```APIDOC
## SSE Functions
### Description
Functions for interacting with Server-Sent Events (SSE) streams.
### Methods
- **DeleteSSE**: Deletes SSE data.
- **GetSSE**: Retrieves SSE data.
- **PatchSSE**: Patches SSE data.
- **PostSSE**: Posts SSE data.
- **PutSSE**: Updates SSE data.
### Endpoints
- `/websites/pkg_go_dev_github_com_starfederation_datastar-go/v1` (example base path)
### Parameters
These functions often accept a URL format string and variadic arguments.
#### Query Parameters
- **urlFormat** (string) - Required - The format string for the URL.
- **args** (...any) - Optional - Additional arguments for the URL format string.
### Request Example
```go
// Example for GetSSE
url := GetSSE("/api/resource/{id}", "123")
// url will be something like "/api/resource/123"
```
### Response
These functions typically return a string representing the constructed URL or an error.
#### Success Response (200)
- **string** - The formatted URL.
#### Error Response
- **error** - If there's an issue formatting the URL or executing the request.
```
```APIDOC
## SSE Options
### Description
Options for configuring Server-Sent Events (SSE) requests and generators.
### Type
`SSEOption` - A functional option type for SSE configurations.
### Functions
- **WithContext**: Adds a context to an SSE option.
### Parameters
- **ctx** (context.Context) - Required - The context to associate with the SSE option.
### Request Example
```go
// Example usage within a function that accepts SSEOption
// handler := NewSSEHandler(WithContext(ctx))
```
```
--------------------------------
### SSE Options
Source: https://pkg.go.dev/github.com/starfederation/datastar-go/%40v1.0.0/datastar
Configuration options for Server-Sent Events, including compression and specific event settings.
```APIDOC
## SSE Options
### Description
Options to configure Server-Sent Events, such as compression strategies and event-specific parameters.
### Options
#### `SSEOption`
* `WithCompression(opts ...CompressionOption) SSEOption`
* **Description**: Configures compression for SSE.
* **Parameters**:
* `opts` ([]CompressionOption) - Optional - Compression options.
#### `CompressionOption`
* `WithBrotli(opts ...BrotliOption) CompressionOption`
* **Description**: Enables Brotli compression.
* **Parameters**:
* `opts` ([]BrotliOption) - Optional - Brotli specific options.
* `WithClientPriority() CompressionOption`
* **Description**: Sets client priority for compression.
* `WithDeflate(opts ...DeflateOption) CompressionOption`
* **Description**: Enables Deflate compression.
* **Parameters**:
* `opts` ([]DeflateOption) - Optional - Deflate specific options.
* `WithForced() CompressionOption`
* **Description**: Forces compression.
* `WithGzip(opts ...GzipOption) CompressionOption`
* **Description**: Enables Gzip compression.
* **Parameters**:
* `opts` ([]GzipOption) - Optional - Gzip specific options.
* `WithServerPriority() CompressionOption`
* **Description**: Sets server priority for compression.
* `WithZstd(opts ...zstd_opts.EOption) CompressionOption`
* **Description**: Enables Zstandard compression.
* **Parameters**:
* `opts` ([]zstd_opts.EOption) - Optional - Zstandard specific options.
#### `BrotliOption`
* `WithBrotliLGWin(lgwin int) BrotliOption`
* **Description**: Sets the LGWIN parameter for Brotli compression.
* **Parameters**:
* `lgwin` (int) - The LGWIN value.
* `WithBrotliLevel(level int) BrotliOption`
* **Description**: Sets the compression level for Brotli.
* **Parameters**:
* `level` (int) - The compression level.
#### `DeflateOption`
* `WithDeflateDictionary(dict []byte) DeflateOption`
* **Description**: Sets a dictionary for Deflate compression.
* **Parameters**:
* `dict` ([]byte) - The dictionary bytes.
* `WithDeflateLevel(level int) DeflateOption`
* **Description**: Sets the compression level for Deflate.
* **Parameters**:
* `level` (int) - The compression level.
#### `GzipOption`
* `WithGzipLevel(level int) GzipOption`
* **Description**: Sets the compression level for Gzip.
* **Parameters**:
* `level` (int) - The compression level.
#### `SSEEventOption`
* `WithSSEEventId(id string) SSEEventOption`
* **Description**: Sets the event ID.
* **Parameters**:
* `id` (string) - The event ID.
* `WithSSERetryDuration(retryDuration time.Duration) SSEEventOption`
* **Description**: Sets the retry duration for the event.
* **Parameters**:
* `retryDuration` (time.Duration) - The retry duration.
#### `DispatchCustomEventOption`
* `WithDispatchCustomEventBubbles(bubbles bool) DispatchCustomEventOption`
* **Description**: Sets whether the custom event bubbles.
* **Parameters**:
* `bubbles` (bool) - True if the event bubbles.
* `WithDispatchCustomEventCancelable(cancelable bool) DispatchCustomEventOption`
* **Description**: Sets whether the custom event is cancelable.
* **Parameters**:
* `cancelable` (bool) - True if the event is cancelable.
* `WithDispatchCustomEventComposed(composed bool) DispatchCustomEventOption`
* **Description**: Sets whether the custom event is composed.
* **Parameters**:
* `composed` (bool) - True if the event is composed.
* `WithDispatchCustomEventEventID(id string) DispatchCustomEventOption`
* **Description**: Sets the event ID for the custom event.
* **Parameters**:
* `id` (string) - The event ID.
* `WithDispatchCustomEventRetryDuration(retryDuration time.Duration) DispatchCustomEventOption`
* **Description**: Sets the retry duration for the custom event.
* **Parameters**:
* `retryDuration` (time.Duration) - The retry duration.
* `WithDispatchCustomEventSelector(selector string) DispatchCustomEventOption`
* **Description**: Sets a CSS selector for the custom event.
* **Parameters**:
* `selector` (string) - The CSS selector.
#### `ExecuteScriptOption`
* `WithExecuteScriptAttributeKVs(kvs ...string) ExecuteScriptOption`
* **Description**: Sets key-value attributes for script execution.
* **Parameters**:
* `kvs` ([]string) - Key-value pairs.
* `WithExecuteScriptAttributes(attributes ...string) ExecuteScriptOption`
* **Description**: Sets general attributes for script execution.
* **Parameters**:
* `attributes` ([]string) - Attributes.
* `WithExecuteScriptAutoRemove(autoremove bool) ExecuteScriptOption`
* **Description**: Specifies if the script should be automatically removed.
* **Parameters**:
* `autoremove` (bool) - True to auto-remove.
* `WithExecuteScriptEventID(id string) ExecuteScriptOption`
* **Description**: Sets the event ID for script execution.
* **Parameters**:
* `id` (string) - The event ID.
* `WithExecuteScriptRetryDuration(retryDuration time.Duration) ExecuteScriptOption`
* **Description**: Sets the retry duration for script execution.
* **Parameters**:
* `retryDuration` (time.Duration) - The retry duration.
#### `PatchElementOption`
* `WithMode(merge ElementPatchMode) PatchElementOption`
* **Description**: Sets the patch mode for element patching.
* **Parameters**:
* `merge` (ElementPatchMode) - The patch mode.
* `WithModeAfter() PatchElementOption`
* **Description**: Sets patch mode to 'after'.
* `WithModeAppend() PatchElementOption`
* **Description**: Sets patch mode to 'append'.
* `WithModeBefore() PatchElementOption`
* **Description**: Sets patch mode to 'before'.
* `WithModeInner() PatchElementOption`
* **Description**: Sets patch mode to 'inner'.
* `WithModeOuter() PatchElementOption`
* **Description**: Sets patch mode to 'outer'.
* `WithModePrepend() PatchElementOption`
* **Description**: Sets patch mode to 'prepend'.
* `WithModeRemove() PatchElementOption`
* **Description**: Sets patch mode to 'remove'.
* `WithModeReplace() PatchElementOption`
* **Description**: Sets patch mode to 'replace'.
* `WithPatchElementsEventID(id string) PatchElementOption`
* **Description**: Sets the event ID for element patching.
* **Parameters**:
* `id` (string) - The event ID.
* `WithRetryDuration(retryDuration time.Duration) PatchElementOption`
* **Description**: Sets the retry duration for element patching.
* **Parameters**:
* `retryDuration` (time.Duration) - The retry duration.
* `WithSelector(selector string) PatchElementOption`
* **Description**: Sets a CSS selector for element patching.
* **Parameters**:
* `selector` (string) - The CSS selector.
* `WithSelectorID(id string) PatchElementOption`
* **Description**: Sets a CSS selector based on an ID for element patching.
* **Parameters**:
* `id` (string) - The element ID.
* `WithSelectorf(selectorFormat string, args ...any) PatchElementOption`
* **Description**: Sets a formatted CSS selector for element patching.
* **Parameters**:
* `selectorFormat` (string) - The format string for the selector.
* `args` ([]any) - Arguments for the format string.
* `WithUseViewTransitions(useViewTransition bool) PatchElementOption`
* **Description**: Enables or disables view transitions for element patching.
* **Parameters**:
* `useViewTransition` (bool) - True to use view transitions.
* `WithViewTransitions() PatchElementOption`
* **Description**: Enables view transitions for element patching.
* `WithoutViewTransitions() PatchElementOption`
* **Description**: Disables view transitions for element patching.
#### `PatchSignalsOption`
* `WithOnlyIfMissing(onlyIfMissing bool) PatchSignalsOption`
* **Description**: Specifies to patch signals only if they are missing.
* **Parameters**:
* `onlyIfMissing` (bool) - True to patch only if missing.
* `WithPatchSignalsEventID(id string) PatchSignalsOption`
* **Description**: Sets the event ID for signal patching.
* **Parameters**:
* `id` (string) - The event ID.
* `WithPatchSignalsRetryDuration(retryDuration time.Duration) PatchSignalsOption`
* **Description**: Sets the retry duration for signal patching.
* **Parameters**:
* `retryDuration` (time.Duration) - The retry duration.
#### `ElementPatchMode`
* `ElementPatchModeFromString(s string) (ElementPatchMode, error)`
* **Description**: Parses an ElementPatchMode from a string.
* **Parameters**:
* `s` (string) - The string representation of the mode.
* **Returns**:
* `ElementPatchMode` - The parsed mode.
* `error` - An error if parsing fails.
### Types
* `CompressionStrategy` (type)
* `Compressor` (type)
* `EventType` (type)
* `GoStarElementRenderer` (interface)
```
--------------------------------
### Read Datastar Signals from HTTP Request (Go)
Source: https://pkg.go.dev/github.com/starfederation/datastar-go/%40v1.0.0/datastar
A function to read and unmarshal Datastar signals from an HTTP request. It handles signals from URL query parameters for GET requests or JSON-encoded bodies for other methods, expecting a pointer to a struct for unmarshaling.
```go
func ReadSignals(r *http.Request, signals any) error
ReadSignals extracts Datastar signals from an HTTP request and unmarshals them into the signals target, which should be a pointer to a struct. Expects signals in [URL.Query] for http.MethodGet requests. Expects JSON-encoded signals in [Request.Body] for other request methods.
```
--------------------------------
### Server-Sent Events Generation
Source: https://pkg.go.dev/github.com/starfederation/datastar-go/%40v1.0.2/datastar
Functions for generating Datastar backend action attributes for Server-Sent Events (SSE). These functions help in creating dynamic attributes for HTTP methods like GET, POST, PUT, PATCH, and DELETE.
```APIDOC
## GET /
### Description
Generates the Datastar backend get action attribute for SSE.
### Method
GET
### Endpoint
N/A (This is a function to generate an attribute string)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```go
attribute := GetSSE("/data/{id}", 123)
// attribute might be something like: "hx-get=\"/data/123\""
```
### Response
#### Success Response (200)
N/A (This function returns a string attribute)
#### Response Example
```
"hx-get=\"/data/123\""
```
## POST /
### Description
Generates the Datastar backend post action attribute for SSE.
### Method
POST
### Endpoint
N/A (This is a function to generate an attribute string)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```go
attribute := PostSSE("/users")
// attribute might be something like: "hx-post=\"/users\""
```
### Response
#### Success Response (200)
N/A (This function returns a string attribute)
#### Response Example
```
"hx-post=\"/users\""
```
## PUT /
### Description
Generates the Datastar backend put action attribute for SSE.
### Method
PUT
### Endpoint
N/A (This is a function to generate an attribute string)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```go
attribute := PutSSE("/items/{id}", 456)
// attribute might be something like: "hx-put=\"/items/456\""
```
### Response
#### Success Response (200)
N/A (This function returns a string attribute)
#### Response Example
```
"hx-put=\"/items/456\""
```
## PATCH /
### Description
Generates the Datastar backend patch action attribute for SSE.
### Method
PATCH
### Endpoint
N/A (This is a function to generate an attribute string)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```go
attribute := PatchSSE("/settings/{key}", "theme")
// attribute might be something like: "hx-patch=\"/settings/theme\""
```
### Response
#### Success Response (200)
N/A (This function returns a string attribute)
#### Response Example
```
"hx-patch=\"/settings/theme\""
```
## DELETE /
### Description
Generates the Datastar backend delete action attribute for SSE.
### Method
DELETE
### Endpoint
N/A (This is a function to generate an attribute string)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```go
attribute := DeleteSSE("/data/{id}", 789)
// attribute might be something like: "hx-delete=\"/data/789\""
```
### Response
#### Success Response (200)
N/A (This function returns a string attribute)
#### Response Example
```
"hx-delete=\"/data/789\""
```
```
--------------------------------
### Configure Brotli Compression Options (Go)
Source: https://pkg.go.dev/github.com/starfederation/datastar-go/datastar
Provides options to configure the Brotli compression algorithm for server-sent events. This includes setting the sliding window size and the compression level.
```go
type BrotliOption func(*brotli.Options)
// BrotliOption configures the Brotli compression algorithm.
```
```go
func WithBrotliLGWin(lgwin int) BrotliOption
// WithBrotliLGWin the sliding window size for Brotli compression algorithm. Select a value between 10 and 24. Defaults to 0, indicating automatic window size selection based on compression quality.
```
```go
func WithBrotliLevel(level int) BrotliOption
// WithBrotliLevel determines the algorithm's compression level. Higher values result in smaller output at the cost of higher CPU usage. Fastest compression level is 0. Best compression level is 11. Defaults to 6.
```
--------------------------------
### Compression Options for SSE in Go
Source: https://pkg.go.dev/github.com/starfederation/datastar-go/datastar
This section details the various compression strategies available for Server-Sent Events (SSE) within the `datastar-go` package. It covers configuration options for Brotli, Deflate, Gzip, and Zstd compression, allowing fine-grained control over compression levels, dictionaries, and other parameters.
```go
package main
import (
"context"
"net/http"
"github.com/starfederation/datastar-go/sse"
"github.com/starfederation/datastar-go/sse/zstd_opts"
)
func main() {
http.HandleFunc("/compressed-sse", func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
// Example: Using Brotli compression with a specific level and window size
brotliOpts := []sse.BrotliOption{
sse.WithBrotliLevel(5),
sse.WithBrotliLGWin(22),
}
// Example: Using Gzip compression
gzipOpts := []sse.GzipOption{
sse.WithGzipLevel(9),
}
// Example: Using Zstd compression with an E-option
zstdOptions := []zstd_opts.EOption{
// Add Zstd options here if needed
}
compressionOpts := []sse.CompressionOption{
sse.WithBrotli(brotliOpts...),
sse.WithGzip(gzipOpts...),
sse.WithZstd(zstdOptions...),
sse.WithDeflate(), // Default deflate
sse.WithServerPriority(), // Example of priority option
}
generator := sse.NewSSE(w, r, sse.WithContext(ctx), sse.WithCompression(compressionOpts...))
// Send SSE data using the generator...
_ = generator.ConsoleLog("This message is sent with compression.")
})
http.ListenAndServe(":8080", nil)
}
```
--------------------------------
### Datastar Go SSE Backend Action Attributes
Source: https://pkg.go.dev/github.com/starfederation/datastar-go/datastar
Convenience methods for generating Datastar backend action attributes for HTTP methods like DELETE, GET, PATCH, POST, and PUT. These functions format a URL string with provided arguments.
```go
func DeleteSSE(urlFormat string, args ...any) string
// DeleteSSE is a convenience method for generating Datastar backend delete action attribute.
```
```go
func GetSSE(urlFormat string, args ...any) string
// GetSSE is a convenience method for generating Datastar backend get action attribute.
```
```go
func PatchSSE(urlFormat string, args ...any) string
// PatchSSE is a convenience method for generating Datastar backend patch action attribute.
```
```go
func PostSSE(urlFormat string, args ...any) string
// PostSSE is a convenience method for generating Datastar backend post action attribute.
```
```go
func PutSSE(urlFormat string, args ...any) string
// PutSSE is a convenience method for generating Datastar backend put action attribute.
```