### Creating HTMX Instance (Go)
Source: https://github.com/dajooo/go-htmx/blob/main/README.md
Provides examples for initializing an HTMX instance using go-htmx. It shows how to create instances for `net/http`, `fasthttp`, and a universal approach that auto-detects the header type.
```go
// For net/http
h := htmx.New(request.Header)
// For fasthttp
h := htmx.NewFastHttp(&request.Header)
// Universal (auto-detects header type)
h := htmx.NewUniversal(header)
```
--------------------------------
### Complete Example with net/http and JSON (Go)
Source: https://github.com/dajooo/go-htmx/blob/main/README.md
A comprehensive example demonstrating how to handle an HTMX request with `net/http`. It includes checking for HTMX requests, processing data, setting multiple HTMX response headers, and sending JSON data within an HTMX trigger event.
```go
package main
import (
"encoding/json"
"net/http"
"github.com/dajooo/go-htmx"
)
type User struct {
ID int `json:"id"`
Name string `json:"name"`
}
func updateUserHandler(w http.ResponseWriter, r *http.Request) {
h := htmx.New(r.Header)
if !h.IsRequest() {
http.Error(w, "HTMX required", http.StatusBadRequest)
return
}
// Get the target element that triggered the request
target := h.GetTarget()
trigger := h.GetTrigger()
// Process the update
user := User{ID: 1, Name: "Updated User"}
// Build response with multiple HTMX directives
h.PushUrl("/users/1").
Trigger("userUpdated").
TriggerAfterSwap("highlight").
Apply(w.Header())
// Send JSON data to trigger client-side event
triggerData := map[string]interface{}{
"user": user,
"message": "User updated successfully",
}
triggerJSON, _ := json.Marshal(triggerData)
h.Response.Trigger = string(triggerJSON)
h.Apply(w.Header())
w.Header().Set("Content-Type", "text/html")
w.Write([]byte(`
` + user.Name + `
`))
}
func main() {
http.HandleFunc("/users/update", updateUserHandler)
http.ListenAndServe(":8080", nil)
}
```
--------------------------------
### Install go-htmx Library
Source: https://github.com/dajooo/go-htmx/blob/main/README.md
This snippet shows the command to install the go-htmx library using the Go package manager. It ensures the library is available for use in your project.
```bash
go get github.com/dajooo/go-htmx
```
--------------------------------
### Complete CRUD with HTMX Integration in Go
Source: https://context7.com/dajooo/go-htmx/llms.txt
This example provides a comprehensive demonstration of building a full CRUD (Create, Read, Update, Delete) application in Go, integrating seamlessly with HTMX for dynamic user interfaces. It covers handling various HTMX requests, building appropriate responses, and managing data operations. The code includes handlers for listing, creating, and deleting tasks, utilizing HTMX directives to update the DOM without full page reloads.
```go
package main
import (
"encoding/json"
"fmt"
"net/http"
"github.com/dajooo/go-htmx"
)
type Task struct {
ID int `json:"id"`
Title string `json:"title"`
Completed bool `json:"completed"`
}
var tasks = []Task{
{ID: 1, Title: "Learn Go", Completed: false},
{ID: 2, Title: "Learn HTMX", Completed: true},
}
func listTasksHandler(w http.ResponseWriter, r *http.Request) {
h := htmx.New(r.Header)
html := "
"
for _, task := range tasks {
status := "pending"
if task.Completed {
status = "completed"
}
html += fmt.Sprintf(`
%s
`, status, task.ID, task.Title, task.ID, task.ID)
}
html += "
", newTask.ID, newTask.Title, newTask.ID, newTask.ID)))
}
func deleteTaskHandler(w http.ResponseWriter, r *http.Request) {
h := htmx.New(r.Header)
if !h.IsRequest() {
http.Error(w, "HTMX required", http.StatusBadRequest)
return
}
// Get task ID from target
target := h.GetTarget()
// Simulate deletion
// tasks = removeTask(taskID)
// Delete element and trigger event
h.Reswap(htmx.SwapDelete).
Trigger("taskDeleted").
TriggerAfterSettle("updateTaskCount").
Apply(w.Header())
w.Write([]byte(fmt.Sprintf("
Task %s deleted
", target)))
}
func main() {
http.HandleFunc("/tasks", listTasksHandler)
http.HandleFunc("/tasks/create", createTaskHandler)
http.HandleFunc("/tasks/", deleteTaskHandler)
http.ListenAndServe(":8080", nil)
}
```
--------------------------------
### Building HTMX Responses with Fluent API (Go)
Source: https://github.com/dajooo/go-htmx/blob/main/README.md
Illustrates the fluent API provided by go-htmx for constructing HTMX responses. This example shows how to chain multiple response methods like `Location`, `PushUrl`, and `Trigger` before applying them to the response header.
```go
h.Location("/users/123").
PushUrl("/users/123").
Trigger("userUpdated").
TriggerAfterSwap("highlight").
Apply(responseHeader)
```
--------------------------------
### Setting Response Location and Navigation
Source: https://context7.com/dajooo/go-htmx/llms.txt
Demonstrates how to control client-side navigation by setting the HX-Location header to guide HTMX on where to navigate.
```APIDOC
## POST /login
### Description
Handles user login attempts. Upon successful authentication, it sets the `HX-Location` header to redirect the user to the dashboard. On failure, it returns an error message without navigation.
### Method
POST
### Endpoint
/login
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **username** (string) - Required - The username for login.
- **password** (string) - Required - The password for login.
### Request Example
```json
{
"username": "admin",
"password": "secret"
}
```
### Response
#### Success Response (200)
- Sets `HX-Location: /dashboard` header.
- Returns an HTML snippet indicating successful login and redirection.
#### Success Response Example
```html
Login successful, redirecting...
```
#### Error Response (e.g., 401 or 200 with error message)
- Returns an HTML snippet with an error message.
#### Error Response Example
```html
Invalid credentials
```
```
--------------------------------
### Reading HTMX Request Information (Go)
Source: https://github.com/dajooo/go-htmx/blob/main/README.md
Shows how to extract specific information from an HTMX request using the go-htmx library. This includes getting the current URL, target element, trigger details, and prompt values.
```go
// Get request details
currentURL := h.Request.CurrentUrl
target := h.GetTarget()
trigger := h.GetTrigger()
triggerName := h.GetTriggerName()
prompt := h.GetPrompt()
```
--------------------------------
### Setting Response Location for Navigation in Go
Source: https://context7.com/dajooo/go-htmx/llms.txt
Control client-side navigation by setting the HX-Location header to tell HTMX where to navigate. This example demonstrates setting the HX-Location header to redirect the user to a different page upon successful login.
```go
package main
import (
"net/http"
"github.com/dajooo/go-htmx"
)
func loginHandler(w http.ResponseWriter, r *http.Request) {
h := htmx.New(r.Header)
// Simulate authentication
username := r.FormValue("username")
password := r.FormValue("password")
if username == "admin" && password == "secret" {
// Navigate to dashboard on success
h.Location("/dashboard").Apply(w.Header())
w.Write([]byte("
Login successful, redirecting...
"))
} else {
// Stay on page and show error
w.Write([]byte(`
Invalid credentials
`))
}
}
func main() {
http.HandleFunc("/login", loginHandler)
http.ListenAndServe(":8080", nil)
}
```
--------------------------------
### Basic Usage with net/http
Source: https://github.com/dajooo/go-htmx/blob/main/README.md
Demonstrates how to use go-htmx with Go's standard `net/http` package. It shows how to create an HTMX instance, check for HTMX requests, apply HTMX response headers, and write HTML content.
```go
package main
import (
"net/http"
"github.com/dajooo/go-htmx"
)
func handler(w http.ResponseWriter, r *http.Request) {
h := htmx.New(r.Header)
// Check if it's an HTMX request
if h.IsRequest() {
// Handle HTMX-specific logic
h.PushUrl("/new-url").Trigger("myEvent").Apply(w.Header())
w.Write([]byte("
Updated content
"))
} else {
// Handle regular HTTP request
w.Write([]byte("Full page"))
}
}
```
--------------------------------
### Usage with fasthttp
Source: https://github.com/dajooo/go-htmx/blob/main/README.md
Illustrates the usage of go-htmx with the `fasthttp` framework. It covers creating an HTMX instance for fasthttp, checking for HTMX requests, and applying HTMX response headers.
```go
package main
import (
"github.com/valyala/fasthttp"
"github.com/dajooo/go-htmx"
)
func handler(ctx *fasthttp.RequestCtx) {
h := htmx.NewFastHttp(&ctx.Request.Header)
if h.IsRequest() {
h.Redirect("/dashboard").Apply(&ctx.Response.Header)
ctx.SetBody([]byte("
Redirecting...
"))
}
}
```
--------------------------------
### Creating HTMX Instance from fasthttp Headers
Source: https://context7.com/dajooo/go-htmx/llms.txt
Initialize an HTMX handler from fasthttp request headers for high-performance applications requiring fast HTTP processing.
```APIDOC
## Creating HTMX Instance from fasthttp Headers
### Description
Initialize an HTMX handler from fasthttp request headers for high-performance applications requiring fast HTTP processing.
### Method
`htmx.NewFastHttp(headers *fasthttp.RequestHeader)`
### Endpoint
N/A (Library function)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```go
package main
import (
"github.com/valyala/fasthttp"
"github.com/dajooo/go-htmx"
)
func fasthttpHandler(ctx *fasthttp.RequestCtx) {
// Create HTMX instance from fasthttp request
h := htmx.NewFastHttp(&ctx.Request.Header)
// Check if request is boosted (hx-boost)
if h.IsBoosted() {
ctx.SetContentType("text/html")
ctx.SetBody([]byte("
Boosted navigation
"))
} else if h.IsRequest() {
ctx.SetBody([]byte("
Standard HTMX request
"))
} else {
ctx.SetBody([]byte("Full page"))
}
}
func main() {
fasthttp.ListenAndServe(":8080", fasthttpHandler)
}
```
### Response
#### Success Response (200)
None (This is a function call, not an endpoint response)
#### Response Example
None
```
--------------------------------
### Creating HTMX Instance from net/http Headers
Source: https://context7.com/dajooo/go-htmx/llms.txt
Initialize an HTMX handler from standard Go HTTP request headers to parse incoming HTMX request data and prepare response directives.
```APIDOC
## Creating HTMX Instance from net/http Headers
### Description
Initialize an HTMX handler from standard Go HTTP request headers to parse incoming HTMX request data and prepare response directives.
### Method
`htmx.New(headers http.Header)`
### Endpoint
N/A (Library function)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```go
package main
import (
"net/http"
"github.com/dajooo/go-htmx"
)
func handler(w http.ResponseWriter, r *http.Request) {
// Create HTMX instance from net/http request
h := htmx.New(r.Header)
// Access parsed request headers
isHtmx := h.IsRequest() // true if HX-Request header present
target := h.GetTarget() // ID of target element
trigger := h.GetTrigger() // ID of triggering element
currentURL := h.Request.CurrentUrl
if isHtmx {
w.Write([]byte("
HTMX Request Detected
"))
} else {
w.Write([]byte("Regular Request"))
}
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
```
### Response
#### Success Response (200)
None (This is a function call, not an endpoint response)
#### Response Example
None
```
--------------------------------
### Client-Side Redirect and Page Refresh
Source: https://context7.com/dajooo/go-htmx/llms.txt
Illustrates how to trigger full client-side redirects or page refreshes by setting the `HX-Redirect` and `HX-Refresh` headers.
```APIDOC
## POST /logout
### Description
Logs out the current user. This endpoint simulates session clearing and then sets the `HX-Redirect` header to navigate the client to the login page.
### Method
POST
### Endpoint
/logout
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
(No explicit request body)
### Response
#### Success Response (200)
- Sets `HX-Redirect: /login` header.
- Returns an HTML snippet indicating logout is in progress.
#### Response Example
```html
Logging out...
```
## POST /account/delete
### Description
Handles account deletion. After simulating account deletion, this endpoint sets the `HX-Refresh` header to `true`, causing the entire page to refresh.
### Method
POST
### Endpoint
/account/delete
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
(No explicit request body)
### Response
#### Success Response (200)
- Sets `HX-Refresh: true` header.
- Returns an HTML snippet confirming account deletion.
#### Response Example
```html
Account deleted
```
```
--------------------------------
### Managing Browser History with PushUrl and ReplaceUrl
Source: https://context7.com/dajooo/go-htmx/llms.txt
Explains how to control browser history using `HX-Push-URL` and `HX-Replace-URL` headers, allowing for URL updates without full page reloads.
```APIDOC
## GET /users/{id}
### Description
Fetches and displays a user profile. This endpoint uses `HX-Push-URL` to add the user's profile URL to the browser history, enabling the back button functionality.
### Method
GET
### Endpoint
/users/{id}
### Parameters
#### Path Parameters
- **id** (string) - Required - The unique identifier for the user.
#### Query Parameters
None
#### Request Body
None
### Request Example
(No explicit request body, relies on URL parameters)
### Response
#### Success Response (200)
- Sets `HX-Push-URL` header with the user's profile URL.
- Returns HTML content for the user profile.
#### Response Example
```html
User Profile: 123
Profile content here...
```
## GET /search
### Description
Handles search requests. This endpoint uses `HX-Replace-URL` to update the URL in the browser's address bar without adding a new entry to the history, suitable for updating search filters.
### Method
GET
### Endpoint
/search
### Parameters
#### Path Parameters
None
#### Query Parameters
- **q** (string) - Required - The search query term.
#### Request Body
None
### Request Example
```
/search?q=golang
```
### Response
#### Success Response (200)
- Sets `HX-Replace-URL` header with the updated search URL.
- Returns HTML content with search results.
#### Response Example
```html
Results for: golang
```
```
--------------------------------
### Initialize HTMX from fasthttp Headers in Go
Source: https://context7.com/dajooo/go-htmx/llms.txt
Initializes an HTMX handler from fasthttp request headers for high-performance applications. It parses HTMX request data and prepares response directives using the fasthttp framework.
```go
package main
import (
"github.com/valyala/fasthttp"
"github.com/dajooo/go-htmx"
)
func fasthttpHandler(ctx *fasthttp.RequestCtx) {
// Create HTMX instance from fasthttp request
h := htmx.NewFastHttp(&ctx.Request.Header)
// Check if request is boosted (hx-boost)
if h.IsBoosted() {
ctx.SetContentType("text/html")
ctx.SetBody([]byte("
Boosted navigation
"))
} else if h.IsRequest() {
ctx.SetBody([]byte("
Standard HTMX request
"))
} else {
ctx.SetBody([]byte("Full page"))
}
}
func main() {
fasthttp.ListenAndServe(":8080", fasthttpHandler)
}
```
--------------------------------
### Go HTMX: Dynamically Change Swap Strategy
Source: https://context7.com/dajooo/go-htmx/llms.txt
Override the default HTMX swap behavior on the fly using the HX-Reswap header. This Go code demonstrates how to apply various predefined swap strategies like prepend, append, replace, and delete based on query parameters. It utilizes the 'go-htmx' library.
```go
package main
import (
"net/http"
"github.com/dajooo/go-htmx"
)
func dynamicSwapHandler(w http.ResponseWriter, r *http.Request) {
h := htmx.New(r.Header)
operation := r.URL.Query().Get("op")
switch operation {
case "prepend":
// Add content at the beginning
h.Reswap(htmx.SwapAfterbegin).Apply(w.Header())
w.Write([]byte("
New item prepended
"))
case "append":
// Add content at the end
h.Reswap(htmx.SwapBeforeend).Apply(w.Header())
w.Write([]byte("
New item appended
"))
case "replace":
// Replace entire element
h.Reswap(htmx.SwapOuterHTML).Apply(w.Header())
w.Write([]byte("Entire element replaced"))
case "delete":
// Delete the target element
h.Reswap(htmx.SwapDelete).Apply(w.Header())
w.Write([]byte(""))
default:
// Default innerHTML swap
h.Reswap(htmx.SwapInnerHTML).Apply(w.Header())
w.Write([]byte("
Content replaced inside
"))
}
}
```
--------------------------------
### Managing Browser History with PushUrl and ReplaceUrl in Go
Source: https://context7.com/dajooo/go-htmx/llms.txt
Control browser history by pushing or replacing URLs without full page reloads using HX-Push-URL and HX-Replace-URL headers. `PushUrl` adds a new entry to the history, while `ReplaceUrl` modifies the current history entry.
```go
package main
import (
"fmt"
"net/http"
"github.com/dajooo/go-htmx"
)
func userProfileHandler(w http.ResponseWriter, r *http.Request) {
h := htmx.New(r.Header)
userID := r.URL.Query().Get("id")
// Push URL to history so back button works
h.PushUrl(fmt.Sprintf("/users/%s", userID)).Apply(w.Header())
w.Write([]byte(fmt.Sprintf("
User Profile: %s
Profile content here...
", userID)))
}
func searchHandler(w http.ResponseWriter, r *http.Request) {
h := htmx.New(r.Header)
query := r.URL.Query().Get("q")
// Replace URL without adding to history (for search filters)
h.ReplaceUrl(fmt.Sprintf("/search?q=%s", query)).Apply(w.Header())
w.Write([]byte(fmt.Sprintf("
Results for: %s
", query)))
}
```
--------------------------------
### Fluent API Chaining for Complex HTMX Responses in Go
Source: https://context7.com/dajooo/go-htmx/llms.txt
This snippet demonstrates how to construct sophisticated HTMX responses by chaining multiple methods provided by the go-htmx library. It allows for cleaner and more readable code when setting various HTMX directives like PushUrl, Retarget, Reswap, and Trigger. It takes HTTP headers as input and applies the configured HTMX directives to the response headers.
```go
package main
import (
"encoding/json"
"fmt"
"net/http"
"github.com/dajooo/go-htmx"
)
type Product struct {
ID int `json:"id"`
Name string `json:"name"`
Price float64 `json:"price"`
}
func addToCartHandler(w http.ResponseWriter, r *http.Request) {
h := htmx.New(r.Header)
productID := r.FormValue("productId")
product := Product{ID: 42, Name: "Go Book", Price: 29.99}
// Build notification event data
notification := map[string]interface{}{
"showNotification": map[string]interface{}{
"message": fmt.Sprintf("Added %s to cart", product.Name),
"type": "success",
},
}
notificationJSON, _ := json.Marshal(notification)
// Chain multiple HTMX directives
h.PushUrl(fmt.Sprintf("/products/%s", productID)).
Retarget("#cart-items").
Reswap(htmx.SwapAfterbegin).
Trigger(string(notificationJSON)).
TriggerAfterSettle("cartUpdated").
Apply(w.Header())
w.Header().Set("Content-Type", "text/html")
w.Write([]byte(fmt.Sprintf("
%s$%.2f
", product.ID, product.Name, product.Price)))
}
func main() {
http.HandleFunc("/cart/add", addToCartHandler)
http.ListenAndServe(":8080", nil)
}
```
--------------------------------
### Initialize HTMX from net/http Headers in Go
Source: https://context7.com/dajooo/go-htmx/llms.txt
Initializes an HTMX handler from standard Go HTTP request headers. Parses incoming HTMX request data and prepares response directives. This method is suitable for applications using the standard net/http package.
```go
package main
import (
"net/http"
"github.com/dajooo/go-htmx"
)
func handler(w http.ResponseWriter, r *http.Request) {
// Create HTMX instance from net/http request
h := htmx.New(r.Header)
// Access parsed request headers
isHtmx := h.IsRequest() // true if HX-Request header present
target := h.GetTarget() // ID of target element
trigger := h.GetTrigger() // ID of triggering element
currentURL := h.Request.CurrentUrl
if isHtmx {
w.Write([]byte("
HTMX Request Detected
"))
} else {
w.Write([]byte("Regular Request"))
}
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
```
--------------------------------
### Client-Side Redirect and Page Refresh in Go
Source: https://context7.com/dajooo/go-htmx/llms.txt
Trigger full client-side redirects or page refreshes using HX-Redirect and HX-Refresh headers. `HX-Redirect` performs a client-side redirect to a new URL, while `HX-Refresh` forces a full page refresh.
```go
package main
import (
"net/http"
"github.com/dajooo/go-htmx"
)
func logoutHandler(w http.ResponseWriter, r *http.Request) {
h := htmx.New(r.Header)
// Clear session (simulated)
// sessionManager.Clear()
// Redirect to login page
h.Redirect("/login").Apply(w.Header())
w.Write([]byte("
Logging out...
"))
}
func deleteAccountHandler(w http.ResponseWriter, r *http.Request) {
h := htmx.New(r.Header)
// Delete account (simulated)
// accountService.Delete(userID)
// Refresh entire page to clear all state
h.Refresh(true).Apply(w.Header())
w.Write([]byte("
Account deleted
"))
}
func main() {
http.HandleFunc("/logout", logoutHandler)
http.HandleFunc("/account/delete", deleteAccountHandler)
http.ListenAndServe(":8080", nil)
}
```
--------------------------------
### Checking HTMX Request Status (Go)
Source: https://github.com/dajooo/go-htmx/blob/main/README.md
Demonstrates various methods to check if an incoming request is an HTMX request. It includes checks for general HTMX requests, boosted requests, and history restore requests, using both static functions and instance methods.
```go
// Check if request is from HTMX
if htmx.IsHtmxRequest(request.Header) { ... }
if htmx.IsFastHttpHtmxRequest(&request.Header) { ... }
// Or using instance methods
if h.IsRequest() { ... }
if h.IsBoosted() { ... }
if h.IsHistoryRestoreRequest() { ... }
```
--------------------------------
### Detect HTMX Requests in Go
Source: https://context7.com/dajooo/go-htmx/llms.txt
Checks if an incoming HTTP request originates from HTMX using static helper functions or instance methods. Supports detection for standard HTMX requests, boosted requests, and history restoration navigations.
```go
package main
import (
"net/http"
"github.com/dajooo/go-htmx"
)
func handler(w http.ResponseWriter, r *http.Request) {
// Method 1: Static function check
if htmx.IsHtmxRequest(r.Header) {
w.Write([]byte("HTMX detected via static function"))
return
}
// Method 2: Instance method check
h := htmx.New(r.Header)
if h.IsRequest() {
w.Write([]byte("HTMX detected via instance"))
return
}
// Method 3: Check for boosted requests
if h.IsBoosted() {
w.Write([]byte("Request via hx-boost"))
return
}
// Method 4: Check for history restoration
if h.IsHistoryRestoreRequest() {
w.Write([]byte("Browser back/forward navigation"))
return
}
w.Write([]byte("Regular HTTP request"))
}
```
--------------------------------
### Go HTMX: Control Response Target and Content Selection
Source: https://context7.com/dajooo/go-htmx/llms.txt
Dynamically change the target element or selection of response content using HX-Retarget and HX-Reselect headers. This allows for more granular control over where and what part of the response updates the DOM. It requires the 'go-htmx' library.
```go
package main
import (
"net/http"
"github.com/dajooo/go-htmx"
)
func conditionalHandler(w http.ResponseWriter, r *http.Request) {
h := htmx.New(r.Header)
action := r.FormValue("action")
if action == "warning" {
// Retarget to warning container instead of original target
h.Retarget("#alert-container").Apply(w.Header())
w.Write([]byte(`
Warning: Action requires confirmation
`))
} else if action == "partial" {
// Reselect only specific part of response
h.Reselect("#main-content").Apply(w.Header())
w.Write([]byte(
"
"
"
This will be swapped
"
"
This will be ignored
"
"
"
))
} else {
w.Write([]byte("
Standard response
"))
}
}
func main() {
http.HandleFunc("/conditional", conditionalHandler)
http.ListenAndServe(":8080", nil)
}
```
--------------------------------
### Reading HTMX Request Information
Source: https://context7.com/dajooo/go-htmx/llms.txt
This section details how to access parsed HTMX request headers to understand the context of incoming requests, including target elements, triggers, and user input.
```APIDOC
## GET /info
### Description
Reads and displays information from an incoming HTMX request, such as the target element, trigger, current URL, and user prompt.
### Method
GET
### Endpoint
/info
### Parameters
#### Query Parameters
None
#### Request Body
None
### Request Example
(No explicit request body, relies on HTMX headers)
### Response
#### Success Response (200)
- **Content-Type**: text/html
- Returns an HTML snippet displaying request details.
#### Response Example
```html
Target: some-element-id
Trigger: trigger-element-id (click)
Current URL: http://example.com/page
User Prompt: User input text
```
```
--------------------------------
### Go HTMX: Trigger Client-Side Events
Source: https://context7.com/dajooo/go-htmx/llms.txt
Trigger custom JavaScript events at different stages of the HTMX lifecycle using HX-Trigger, HX-Trigger-After-Swap, and HX-Trigger-After-Settle headers. This Go code shows how to send simple events, events with JSON data, and a cascade of events. It depends on the 'go-htmx' library.
```go
package main
import (
"encoding/json"
"net/http"
"github.com/dajooo/go-htmx"
)
func eventHandler(w http.ResponseWriter, r *http.Request) {
h := htmx.New(r.Header)
// Trigger simple event immediately after response received
h.Trigger("itemUpdated").Apply(w.Header())
w.Write([]byte("
Item updated
"))
}
func multiEventHandler(w http.ResponseWriter, r *http.Request) {
h := htmx.New(r.Header)
// Trigger event with JSON data after swap completes
eventData := map[string]interface{}{
"userId": 123,
"status": "active",
"message": "User activated successfully",
}
jsonData, _ := json.Marshal(eventData)
h.TriggerAfterSwap(string(jsonData)).Apply(w.Header())
w.Write([]byte("
User activated
"))
}
func cascadeEventHandler(w http.ResponseWriter, r *http.Request) {
h := htmx.New(r.Header)
// Trigger events at different lifecycle stages
h.Trigger("beforeSwap").
TriggerAfterSwap("afterSwap").
TriggerAfterSettle("afterSettle").
Apply(w.Header())
w.Write([]byte("
Event cascade triggered
"))
}
```
--------------------------------
### Detecting HTMX Requests
Source: https://context7.com/dajooo/go-htmx/llms.txt
Check if an incoming HTTP request originates from HTMX using static helper functions or instance methods.
```APIDOC
## Detecting HTMX Requests
### Description
Check if an incoming HTTP request originates from HTMX using static helper functions or instance methods.
### Methods
1. `htmx.IsHtmxRequest(headers http.Header)`: Static function to check for `HX-Request` header.
2. `htmx.New(headers http.Header).IsRequest()`: Instance method to check for `HX-Request` header.
3. `htmx.New(headers http.Header).IsBoosted()`: Instance method to check for `HX-Boost` header.
4. `htmx.New(headers http.Header).IsHistoryRestoreRequest()`: Instance method to check for `HX-History-Restore-Request` header.
### Endpoint
N/A (Library functions)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```go
package main
import (
"net/http"
"github.com/dajooo/go-htmx"
)
func handler(w http.ResponseWriter, r *http.Request) {
// Method 1: Static function check
if htmx.IsHtmxRequest(r.Header) {
w.Write([]byte("HTMX detected via static function"))
return
}
// Method 2: Instance method check
h := htmx.New(r.Header)
if h.IsRequest() {
w.Write([]byte("HTMX detected via instance"))
return
}
// Method 3: Check for boosted requests
if h.IsBoosted() {
w.Write([]byte("Request via hx-boost"))
return
}
// Method 4: Check for history restoration
if h.IsHistoryRestoreRequest() {
w.Write([]byte("Browser back/forward navigation"))
return
}
w.Write([]byte("Regular HTTP request"))
}
```
### Response
#### Success Response (200)
None (This is a function call, not an endpoint response)
#### Response Example
None
```
--------------------------------
### HTMX Request Headers
Source: https://github.com/dajooo/go-htmx/blob/main/README.md
The go-htmx library automatically parses and makes available the following HTMX request headers.
```APIDOC
## HTMX Request Headers
The library automatically parses these HTMX request headers:
- `HX-Request` - (Boolean) Always true for HTMX requests.
- `HX-Boosted` - (Boolean) True if the request is via `hx-boost`.
- `HX-Current-URL` - (String) The current page URL.
- `HX-History-Restore-Request` - (Boolean) True if the request is from history restoration.
- `HX-Prompt` - (String) The user's response from `hx-prompt`.
- `HX-Target` - (String) The ID of the target element.
- `HX-Trigger` - (String) The ID of the element that triggered the request.
- `HX-Trigger-Name` - (String) The name of the element that triggered the request.
```
--------------------------------
### HTMX Response Headers
Source: https://github.com/dajooo/go-htmx/blob/main/README.md
The go-htmx library can set the following HTMX response headers to control client-side behavior.
```APIDOC
## HTMX Response Headers
The library can set these HTMX response headers:
- `HX-Location` - (String) Navigate the client to the specified URL.
- `HX-Push-URL` - (String) Push the specified URL to the browser's history.
- `HX-Redirect` - (String) Perform a client-side redirect to the specified URL.
- `HX-Refresh` - (Boolean) Force a page refresh.
- `HX-Replace-URL` - (String) Replace the current URL in the browser's history.
- `HX-Reswap` - (String) Change the swap behavior for the response content.
- `HX-Retarget` - (String) Change the target element for the response content.
- `HX-Reselect` - (String) Change the selection mechanism for the response content.
- `HX-Trigger` - (String) Trigger client-side events after the response is settled.
- `HX-Trigger-After-Settle` - (String) Trigger client-side events after the response is settled.
- `HX-Trigger-After-Swap` - (String) Trigger client-side events after the response is swapped.
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.