htmx

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 3, 2023 License: MIT Imports: 5 Imported by: 1

README ¶

go-htmx

Go Reference Go Report Card License MIT


About

go-htmx is a helper library for setting and reading htmx headers.

Main Features

  • 🏔️ High-Level wrapper around the htmx headers
  • ✏️ Overwrite header values by calling setters multiple times
  • đź“– Fully documented—so you read the header's docs directly in your IDE
  • âś… Proper JSON handling

Examples

👓️ Reading Request Headers

The headers set by htmx can be retrieved by calling htmx.Request.

If htmx.Request returns nil htmx.RequestHeaders, the request was not made by htmx.

func retrieveHeaders(r *http.Request, w http.ResponseWriter) {
    fmt.Println("boosted:", htmx.Request(r).Boosted)
    fmt.Println("current url:", htmx.Request(r).CurrentURL)
    // you get the idea...
}

✏️ Setting Response Headers

To add response headers, you first need to add the htmx middleware.

By using a middleware instead of setting headers directly you can overwrite response headers at a later point in your code. This is useful if you have a default value for a header that only changes in certain cases.

It also means you can add event triggers one by one and don't have to set them at once.

For chi, adding the middleware could look like this:

r := chi.NewRouter()
r.Use(htmx.NewMiddleware())

The middleware will add the headers once the first call to http.ResponseWriter.Write is made.

After you've added the middleware, you can start setting headers:

type reloadNavData struct {
	ActiveEntry string
}

func setHeaders(r *http.Request, w http.ResponseWriter) {
    htmx.Retarget(r, "#main")
    htmx.Trigger(r, "reload-nav", reloadNavData{ActiveEntry: "foo"})
    htmx.Trigger(r, "update-cart", nil)
	
    // HX-Retarget: #main 
    // HX-Trigger: {"reload-nav": {"ActiveEntry": "foo"}, "update-cart": null}
}

You can find the full list of setters on pkg.go.dev.

License

Built with ❤ by Maximilian von Lindern. Available under the MIT License.

Documentation ¶

Index ¶

Constants ¶

This section is empty.

Variables ¶

This section is empty.

Functions ¶

func Location ¶

func Location(r *http.Request, loc LocationData) error

Location allows you to do a client-side redirect that does not do a full page reload.

This response header can be used to trigger a client side redirection without reloading the whole page. Instead of changing the page’s location it will act like following a hx-boost link, creating a new history entry, issuing an ajax request to the value of the header and pushing the path into history.

A sample response would be:

HX-LocationData: /test

Which would push the client to test as if the user had clicked on <a href="/test" hx-boost="true">.

If you want to redirect to a specific target on the page rather than the default of document.body, you can pass more details along with the event, by setting the remaining Location values.

If LocationData.Path is an empty string, the location is not included.

Previous values are overwritten.

func LocationPath ¶

func LocationPath(r *http.Request, path URL)

LocationPath is a shorthand for Location(r, LocationData{Path: path}).

func NewMiddleware ¶

func NewMiddleware() func(next http.Handler) http.Handler

NewMiddleware returns a new middleware that adds htmx headers, set by handlers called after this middleware, to the response.

func PreventPushURL ¶

func PreventPushURL(r *http.Request)

PreventPushURL sets the HX-PushURL Header to "false".

It is equivalent to calling PushURL(r, "false").

Previous values are overwritten.

func PreventReplaceURL ¶

func PreventReplaceURL(r *http.Request)

PreventReplaceURL sets the HX-ReplaceURL Header to "false".

It is equivalent to calling ReplaceURL(r, "false").

Previous values are overwritten.

func PushURL ¶

func PushURL(r *http.Request, u SameOriginURL)

PushURL pushes a new url into the history stack:

The HX-Push-Url header allows you to push a URL into the browser location history. This creates a new history entry, allowing navigation with the browser’s back and forward buttons. This is similar to the hx-push-url attribute.

If present, this header overrides any behavior defined with attributes.

To prevent the browser's history from being updated set PushURL to "false".

The URL must be from the same origin as the request.

Previous values are overwritten.

func Redirect ¶

func Redirect(r *http.Request, u URL)

Redirect can be used to do a client-side redirect to a new location.

Previous values are overwritten.

func Refresh ¶

func Refresh(r *http.Request, refresh bool)

Refresh if set to “true”, will do a full refresh of the page on the client side.

Previous values are overwritten.

func ReplaceURL ¶

func ReplaceURL(r *http.Request, u SameOriginURL)

ReplaceURL allows you to replace the current URL in the browser location history. This does not create a new history entry; in effect, it removes the previous current URL from the browser’s history. This is similar to the hx-replace-url attribute.

If present, this header overrides any behavior defined with attributes.

To prevent the browser's current URL from being updated, set ReplaceURL to "false".

The URL must be from the same origin as the request.

Previous values are overwritten.

func Reselect ¶

func Reselect(r *http.Request, sel Selector)

Reselect is a CSS selector that allows you to choose which part of the response is used to be swapped in.

Previous values are overwritten.

func Reswap ¶

func Reswap(r *http.Request, strategy SwapStrategy)

Reswap allows you to specify how the response will be swapped.

Previous values are overwritten.

func Retarget ¶

func Retarget(r *http.Request, sel Selector)

Retarget is a CSS selector that updates the target of the content update to a different element on the page.

Previous values are overwritten.

func Trigger ¶

func Trigger(r *http.Request, name Event, data any) error

Trigger triggers the passed event as soon as the response is received.

If a there already is a trigger for that event, it will be overwritten.

An error will only be returned if data can't be marshalled to json. It is guaranteed that Trigger will never return an error for nil data.

func TriggerAfterSettle ¶

func TriggerAfterSettle(r *http.Request, name Event, data any) error

TriggerAfterSettle triggers the passed event after the settling step.

If a there already is an after-settle trigger for that event, it will be overwritten.

An error will only be returned if data can't be marshalled to json. It is guaranteed that TriggerAfterSettle will never return an error for nil data.

func TriggerAfterSwap ¶

func TriggerAfterSwap(r *http.Request, name Event, data any) error

TriggerAfterSwap triggers the passed event after the swap step.

If a there already is an after-swap trigger for that event, it will be overwritten.

An error will only be returned if data can't be marshalled to json. It is guaranteed that TriggerAfterSwap will never return an error for nil data.

Types ¶

type Element ¶

type Element = string

Aliases for easier understanding of fields.

type Event ¶

type Event = string

Aliases for easier understanding of fields.

type Headers ¶

type Headers map[string]string

type ID ¶

type ID = string

Aliases for easier understanding of fields.

type JS ¶

type JS = string

Aliases for easier understanding of fields.

type JSON ¶

type JSON = json.RawMessage

Aliases for easier understanding of fields.

type LocationData ¶ added in v1.0.0

type LocationData struct {
	// Path is required and is url to load the response from.
	Path URL
	// Source is the source element of the request.
	Source Selector
	// Event is an event that “triggered” the request.
	Event Event
	// Handler is a callback that will handle the response HTML.
	Handler JS
	// Target is the target to swap the response into.
	Target Selector
	// Swap determines how the response will be swapped in relative to the
	// target.
	Swap SwapStrategy
	// Values are the values to submit with the request.
	Values any
	// Headers are the headers to submit with the request.
	Headers Headers
}

LocationData is a location used as the HX-LocationData response header.

See: https://htmx.org/headers/hx-location

type LocationHeader ¶ added in v1.0.0

type LocationHeader struct {
	// Path is required and is url to load the response from.
	Path URL `json:"path,omitempty"`
	// Source is the source element of the request.
	Source Selector `json:"source,omitempty"`
	// Event is an event that “triggered” the request.
	Event Event `json:"event,omitempty"`
	// Handler is a callback that will handle the response HTML.
	Handler JS `json:"handler,omitempty"`
	// Target is the target to swap the response into.
	Target Selector `json:"target,omitempty"`
	// Swap determines how the response will be swapped in relative to the
	// target.
	Swap SwapStrategy `json:"swap,omitempty"`
	// Values are the values to submit with the request.
	Values JSON `json:"values,omitempty"`
	// Headers are the headers to submit with the request.
	Headers Headers `json:"headers,omitempty"`
}

LocationHeader is a location used as the HX-Location response header.

See: https://htmx.org/headers/hx-location

func (*LocationHeader) HeaderValue ¶ added in v1.0.0

func (loc *LocationHeader) HeaderValue() string

type RequestHeaders ¶

type RequestHeaders struct {
	// Boosted indicates that the request is via an element using hx-boost.
	Boosted bool
	// CurrentURL is the current URL of the browser.
	CurrentURL URL
	// HistoryRestoreRequest is set to true, if the request is for history
	// restoration after a miss in the local history cache.
	HistoryRestoreRequest bool
	// Prompt is the user response to an hx-prompt.
	Prompt string
	// Target is the id of the target element, if it exists.
	Target ID
	// TriggerName is the name of the triggered element if it exists.
	TriggerName Element
	// Trigger is the id of the triggered element if it exists.
	Trigger ID
}

RequestHeaders contains the headers set in an htmx request.

The docs of the fields are copied from the website.

See: https://htmx.org/reference/#request_headers

func Request ¶

func Request(r *http.Request) *RequestHeaders

Request returns the htmx RequestHeaders for the current request.

If the request was not made by htmx (as determined by the lack of the "HX-Request" header), Request returns nil.

This function works without the middleware in place.

type ResponseHeaders ¶

type ResponseHeaders struct {
	// Location allows you to do a client-side redirect that does not do a
	// full page reload.
	//
	// This response header can be used to trigger a client side
	// redirection without reloading the whole page.
	// Instead of changing the page’s location it will act like following a
	// hx-boost link, creating a new history entry, issuing an ajax request
	// to the value of the header and pushing the path into history.
	//
	// A sample response would be:
	//
	//	HX-LocationData: /test
	//
	// Which would push the client to test as if the user had clicked on
	// <a href="/test" hx-boost="true">.
	//
	// If you want to redirect to a specific target on the page rather than
	// the default of document.body, you can pass more details along with
	// the event, by setting the remaining Location values.
	//
	// If LocationData.Path is an empty string, the location is not
	// included.
	Location LocationHeader
	// PushURL pushes a new url into the history stack:
	//
	// The HX-Push-Url header allows you to push a URL into the browser
	// location history.
	// This creates a new history entry, allowing navigation with the
	// browser’s back and forward buttons.
	// This is similar to the hx-push-url attribute.
	//
	// If present, this header overrides any behavior defined with
	// attributes.
	//
	// To prevent the browser's history from being updated set PushURL to
	// "false".
	//
	// The URL must be from the same origin as the request.
	PushURL SameOriginURL
	// Redirect can be used to do a client-side redirect to a new location.
	Redirect URL
	// Refresh, if set to “true”, will do a full refresh of the page on the
	// client side.
	Refresh bool
	// ReplaceURL allows you to replace the current URL in the browser
	// location history.
	// This does not create a new history entry; in effect, it removes the
	// previous current URL from the browser’s history.
	// This is similar to the hx-replace-url attribute.
	//
	// If present, this header overrides any behavior defined with
	// attributes.
	//
	// To prevent the browser's current URL from being updated, set
	// ReplaceURL to "false".
	//
	// The URL must be from the same origin as the request.
	ReplaceURL SameOriginURL
	// Reswap allows you to specify how the response will be swapped.
	Reswap SwapStrategy
	// Retarget is a CSS selector that updates the target of the content
	// update to a different element on the page.
	Retarget Selector
	// Reselect is a CSS selector that allows you to choose which part of
	// the response is used to be swapped in.
	//
	// Overrides an existing hx-select on the triggering element.
	Reselect Selector
	// Trigger triggers events as soon as the response is received.
	Trigger map[Event]JSON
	// TriggerAfterSettle triggers events after the settling step.
	TriggerAfterSettle map[Event]JSON
	// TriggerAfterSwap triggers JSON after the swap step.
	TriggerAfterSwap map[Event]JSON
}

ResponseHeaders are the headers that can be sent in response to an htmx request.

The docs of the fields are copied from the website.

See: https://htmx.org/reference#response_headers

func Response ¶

func Response(r *http.Request) *ResponseHeaders

Response returns a pointer to the response headers that will be sent back.

It must be called after the middleware has executed.

func (*ResponseHeaders) AddHeaders ¶

func (h *ResponseHeaders) AddHeaders(header http.Header)

type SameOriginURL ¶

type SameOriginURL = string

Aliases for easier understanding of fields.

type Selector ¶

type Selector = string

Aliases for easier understanding of fields.

type SwapStrategy ¶

type SwapStrategy string
const (
	SwapInnerHTML   SwapStrategy = "innerHTML"
	SwapOuterHTML   SwapStrategy = "outerHTML"
	SwapBeforeBegin SwapStrategy = "beforebegin"
	SwapAfterBegin  SwapStrategy = "afterbegin"
	SwapBeforeEnd   SwapStrategy = "beforeend"
	SwapAfterEnd    SwapStrategy = "afterend"
	SwapDelete      SwapStrategy = "delete"
	SwapNone        SwapStrategy = "none"
)

type URL ¶

type URL = string

Aliases for easier understanding of fields.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL