URL Parameters

Passing URL params to Components is not straightforward in HLive. Here is an example of how to do it.

This is due to HLive having a two-step process of loading a page, and Components are primarily designed to get data from Events.

Live Demo

This example reads query parameters from its own address bar, which isn't reachable when the page is embedded in an iframe.

Open live demo in a new tab ↗

Source

package examples import ( "context" "net/http" l "github.com/SamHennessy/hlive" . "github.com/SamHennessy/hlive/hhtml" "github.com/SamHennessy/hlive/hlivekit" ) // URLParametersDemo serves a live, interactive instance of the URL // Parameters example for the "Live Demo" link. It needs its query-param // middleware wired around the page server, so it returns an http.Handler // instead of a plain *l.Page. func URLParametersDemo() http.Handler { return http.HandlerFunc(urlParamsMiddleware(l.NewPageServer(urlParamsPage).ServeHTTP)) } func urlParamsPage() *l.Page { page := l.NewPage() page.DOM().Title().Add("URL Params Example") page.DOM().Head().Add(Link(Rel("stylesheet"), Href("https://cdn.simplecss.org/simple.min.css"))) page.DOM().Body().Add( Header( H1("URL Get Parameter Read Example"), P("This example reads the parameters from the URL and prints them in a table."), ), Main( P("Add your own query parameters to the url and load the page again."), H2("Values"), ), ) cl := hlivekit.List("tbody") // This is a ComponentMountable, needed so the list can mount rows added // after the initial page load. cm := l.CM("table", Thead( Tr( Th("Key"), Th("Value"), ), ), cl, ) cm.SetMount(func(ctx context.Context) { for key, value := range urlParamsFromCtx(ctx) { cl.AddItem(l.CM("tr", Td(key), Td(value), )) } }) page.DOM().Body().Add( cm, P("You will see the extra 'hlive' parameter that HLive adds on when establishing a WebSocket connection."), ) return page } type urlParamsCtxKey string const ctxURLParams urlParamsCtxKey = "url" func urlParamsMiddleware(h http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { // Only on WebSocket requests if r.URL.Query().Get("hlive") != "" { params := map[string]string{} for key := range r.URL.Query() { params[key] = r.URL.Query().Get(key) } r = r.WithContext(context.WithValue(r.Context(), ctxURLParams, params)) } h(w, r) } } func urlParamsFromCtx(ctx context.Context) map[string]string { params, ok := ctx.Value(ctxURLParams).(map[string]string) if ok && params != nil { return params } return map[string]string{} }