### Display Install Prompt Programmatically Source: https://github.com/maxence-charriere/go-app/blob/master/docs/web/documents/install.md Call the `ShowAppInstallPrompt` method from the Context to display the browser's install prompt when the app is detected as installable. This is typically triggered by a user action, like clicking an install button. ```go func (h *hello) Render() app.UI { return app.Div(). Body( app.H1().Text("Hello World!"), app.If(h.isAppInstallable, func() app.UI { return app.Button(). Text("Install App"). OnClick(h.onInstallButtonClicked) }), ) } func (h *hello) onInstallButtonClicked(ctx app.Context, e app.Event) { ctx.ShowAppInstallPrompt() } ``` -------------------------------- ### Basic Component Implementation Example Source: https://github.com/maxence-charriere/go-app/blob/master/docs/web/documents/reference.html Example of implementing the Composer interface by embedding app.Compo and defining the Render method for a custom component. ```go type Hello struct { app.Compo } func (c *Hello) Render() app.UI { return app.Text("hello") } ``` -------------------------------- ### Detect App Installability Source: https://github.com/maxence-charriere/go-app/blob/master/docs/web/documents/install.md Use the `IsAppInstallable` method from the Context to check if the application can be installed. Implement the `AppInstaller` interface to receive updates on the installable state. ```go type hello struct { app.Compo name string isAppInstallable bool } func (h *hello) OnMount(ctx app.Context) { h.isAppInstallable = ctx.IsAppInstallable() } ``` ```go func (h *hello) OnAppInstallChange(ctx app.Context) { h.isAppInstallable = ctx.IsAppInstallable() } ``` -------------------------------- ### Start HTTP Server with Go-app Handler Source: https://github.com/maxence-charriere/go-app/wiki/HTTP-Handler Use the standard http package to start a server and listen on a specific port using the configured app handler. Ensure error handling is in place. ```go err := http.ListenAndServe(":7000", h) if err != nil { // handle error } ``` -------------------------------- ### Composing Components Example Source: https://github.com/maxence-charriere/go-app/wiki/Components Illustrates how components can be composed by having one component render another. This example shows a 'foo' component that includes a 'bar' component. ```go // foo component type foo struct { app.Compo } func (f *foo) Render() app.UI { return app.P().Body( app.Text("Foo, "), &bar{}, // <-- bar component ) } // bar component type bar struct { app.Compo } func (b *bar) Render() app.UI { return app.Text("Bar!") } ``` -------------------------------- ### Check Go Installation Source: https://github.com/maxence-charriere/go-app/blob/master/docs/web/documents/getting-started.md Verify that Go version 1.18 or greater is installed on your system. ```bash go version ``` -------------------------------- ### Install go-tooling/pkg/errors Source: https://github.com/maxence-charriere/go-app/blob/master/pkg/errors/README.md Install the errors package using go get. ```sh go get -u github.com/aukilabs/go-tooling/pkg/errors ``` -------------------------------- ### Install Go-app Package Source: https://github.com/maxence-charriere/go-app/blob/master/README.md Installs the go-app package using Go modules. Requires Go 1.18 or newer. ```sh go mod init go get -u github.com/maxence-charriere/go-app/v11/pkg/app ``` -------------------------------- ### Example: Testing a Component's H1 Content Source: https://github.com/maxence-charriere/go-app/blob/master/docs/web/documents/testing.md An example demonstrating how to test the content of an H1 element within a component after it mounts. It uses TestMatch to compare the actual UI with the expected UI. ```go type aTitle struct { app.Compo title string } func (t *aTitle) OnMount(ctx app.Context) { t.title = "Testing Mounting" } func (t *aTitle) Render() app.UI { return app.H1(). Class("title"). Text(t.title) } func TestUIElement(t *testing.T) { compo := &aTitle{} disp := app.NewClientTester(compo) defer disp.Close() app.TestMatch(compo, app.TestUIDescriptor{ Path: app.TestPath(0), // Component root. Expected: app.H2().Text("Testing Mounting"), }) } ``` -------------------------------- ### Hello World Component Example Source: https://github.com/maxence-charriere/go-app/wiki/Components A basic component demonstrating rendering text and an input field, with an event handler for input changes. It embeds app.Compo and implements the Render and OnInputChange methods. ```go type hello struct { app.Compo name string } func (h *hello) Render() app.UI { return app.Div().Body( app.H1().Body( app.Text("Hello "), app.Text(h.name), ), app.Input(). Value(h.name). OnChange(h.OnInputChange), ) } func (h *hello) OnInputChange(ctx app.Context, e app.Event) { h.name = ctx.JSSrc().Get("value").String() h.Update() } ``` -------------------------------- ### Run App on Client-Side (V8) Source: https://github.com/maxence-charriere/go-app/blob/master/docs/web/documents/v7-to-v8.md Starting the app on the client-side can now be called in the same code as the server-side. Build instructions and server/client code separation are not required anymore. ```go func RunWhenOnBrowser() ``` -------------------------------- ### AppInstaller Source: https://github.com/maxence-charriere/go-app/blob/master/docs/web/documents/reference.html Outlines components that receive notifications about changes in the application's installation status. Through this interface, components can actively respond to installation state transitions, facilitating dynamic user experiences tailored to the app's current status. ```APIDOC ## type AppInstaller interface ### Description Outlines components that receive notifications about changes in the application's installation status. Through this interface, components can actively respond to installation state transitions, facilitating dynamic user experiences tailored to the app's current status. ### Methods #### OnAppInstallChange(ctx Context) - **Description**: Invoked when the application shifts between the states of being installable and actually installed. - **Context**: To determine the current installation state, one can use Context.IsAppInstallable() or Context.IsAppInstalled(). - **Usage**: By leveraging this method, components can maintain alignment with the app's installation status, potentially influencing UI elements like an "Install" button visibility or behavior. - **Execution Context**: This method is always executed in the UI goroutine context. ``` -------------------------------- ### Basic Hello World Component Source: https://github.com/maxence-charriere/go-app/blob/master/docs/web/documents/seo.md A simple go-app component that renders a "Hello World!" heading. This is a foundational example for creating UI elements. ```go type hello struct { app.Compo } func (h *hello) Render() app.UI { return app.H1().Text("Hello World!") } ``` -------------------------------- ### Initialize Go Module and Get go-app Package Source: https://github.com/maxence-charriere/go-app/wiki/Home Initializes a new Go module if one doesn't exist and then fetches the go-app package. Ensure you are in your project's root directory before running. ```sh # Init go module (if not initialized): go mod init # Get package: go get -u -v github.com/maxence-charriere/go-app/v7 ``` -------------------------------- ### CLI Help Output Example Source: https://github.com/maxence-charriere/go-app/blob/master/pkg/cli/README.md When the `-h` flag is used, the CLI tool displays usage information, including the program description, available options, their types, environment variable mappings, and default values. ```text ▶ ./my-program -h Usage: hds [options] Description: A demo cli program Options: -string string A string argmument for demo purpose. Env: CONF_STRING -int int A int argmument for demo purpose. Env: CONF_INT Default: 42 -h bool Show help. ``` -------------------------------- ### HTTP Handler Setup for Push Notifications Source: https://github.com/maxence-charriere/go-app/blob/master/docs/web/documents/notifications-push.md Sets up an HTTP handler for managing push notification registrations and tests. Requires VAPID private and public keys for authentication. ```go func main() { // ... http.Handle("/test/notifications/", ¬ificationHandler{ VAPIDPrivateKey: "MY_VAPID_PRIVATE_KEY", VAPIDPublicKey: "MY_VAPID_PUBLIC_KEY", }) // ... } type notificationHandler struct { VAPIDPrivateKey string VAPIDPublicKey string mutex sync.Mutex subscriptions map[string]webpush.Subscription } func (h *notificationHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { switch path := path.Base(r.URL.Path); path { case "register": h.handleRegistrations(w, r) case "test": h.handleTests(w, r) } } ``` -------------------------------- ### Nested Components Example Source: https://github.com/maxence-charriere/go-app/blob/master/docs/web/documents/declarative-syntax.md Demonstrates how to embed one component within another. The 'foo' component renders a text element and an instance of the 'bar' component. ```go package main import "maxence-charriere.com/go-app" // foo component: type foo struct { app.Compo } func (f *foo) Render() app.UI { return app.P().Body( app.Text("Foo, "), // Simple HTML text &bar{}, // Nested bar component ) } // bar component: type bar struct { app.Compo } func (b *bar) Render() app.UI { return app.Text("Bar!") } ``` -------------------------------- ### Build and Test WebAssembly App with go-app Source: https://github.com/maxence-charriere/go-app/wiki/Home Commands to build a WebAssembly binary for your app and set up the necessary environment for testing. This includes installing a test runner and executing Go tests for the wasm target. ```sh # Build wasm app: GOARCH=wasm GOOS=js go build -o app.wasm # Install wasm test env: go get -u github.com/agnivade/wasmbrowsertest && \ mv $GOPATH/bin/wasmbrowsertest $GOPATH/bin/go_js_wasm_exec # Test wasm app: GOARCH=wasm GOOS=js go test ``` -------------------------------- ### Create JS Object (Go Equivalent) Source: https://github.com/maxence-charriere/go-app/blob/master/docs/web/documents/js.md Instantiate a JavaScript object from a global constructor, such as YT.Player, using the Get and New methods on the Window object. This is the Go equivalent of 'new YT.Player(...)'. ```go player := app.Window(). Get("YT"). Get("Player"). New("yt-container", map[string]interface{}{ "height": 390, "width": 640, "videoId": "M7lc1UVf-VE", }) ``` -------------------------------- ### Build and Run Static Website Generation Source: https://github.com/maxence-charriere/go-app/blob/master/docs/web/documents/github-deploy.md These commands demonstrate how to build the WebAssembly binary and then build and run the go executable to generate the static website files. ```sh # Build app.wasm: GOARCH=wasm GOOS=js go build -o /test-app/web/app.wasm # Build and generate static website: go build ./hello ``` -------------------------------- ### Get DOM Element by ID (JS Helper) Source: https://github.com/maxence-charriere/go-app/blob/master/docs/web/documents/js.md An alternative way to get a DOM element by ID using the Get and Call methods on the Window object, mimicking JavaScript's document.getElementById. ```go elem := app.Window(). Get("document"). Call("getElementById","YOUR_ID") ``` -------------------------------- ### Hello World Component with Declarative Syntax Source: https://github.com/maxence-charriere/go-app/blob/master/README.md A basic 'Hello World' component demonstrating declarative UI creation with input handling and conditional rendering in go-app. ```go type hello struct { app.Compo name string } func (h *hello) Render() app.UI { return app.Div().Body( app.H1().Body( app.Text("Hello, "), app.If(h.name != "", func() app.UI { return app.Text(h.name) }).Else(func() app.UI { return app.Text("World!") }), ), app.P().Body( app.Input(). Type("text"). Value(h.name). Placeholder("What is your name?"). AutoFocus(true). OnChange(h.ValueTo(&h.name)), ), ) } ``` -------------------------------- ### App Routing and Execution Source: https://github.com/maxence-charriere/go-app/blob/master/docs/start.md Sets up routing for the 'Hello World' component and configures the application to run in the browser. It also defines the HTTP handler for serving the application. ```go func main() { app.Route("/", newHello) app.RunWhenOnBrowser() http.Handle("/", &app.Handler{ Name: "Hello", Description: "A Hello World example", }) if err := http.ListenAndServe(":8000", nil); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Install WASM Browser Test Runner Source: https://github.com/maxence-charriere/go-app/wiki/Build-and-deploy Installs the wasmbrowsertest tool, which is required for running Go unit tests in a browser environment. This tool needs to be reinstalled after Go updates. ```sh go get -u github.com/agnivade/wasmbrowsertest && \ mv $GOPATH/bin/wasmbrowsertest $GOPATH/bin/go_js_wasm_exec ``` -------------------------------- ### Main Function for App Configuration and Execution Source: https://github.com/maxence-charriere/go-app/blob/master/docs/web/documents/getting-started.md Sets up the application's routes, handles browser execution, and configures the HTTP server. This function runs on both the client and server. ```go // The main function is the entry point where the app is configured and started. // It is executed in 2 different environments: A client (the web browser) and a // server. func main() { // The first thing to do is to associate the hello component with a path. // // This is done by calling the Route() function, which tells go-app what // component to display for a given path, on both client and server-side. app.Route("/", func() app.Composer { return &hello{} }) // Once the routes set up, the next thing to do is to either launch the app // or the server that serves the app. // // When executed on the client-side, the RunWhenOnBrowser() function // launches the app, starting a loop that listens for app events and // executes client instructions. Since it is a blocking call, the code below // it will never be executed. // // When executed on the server-side, RunWhenOnBrowser() does nothing, which // lets room for server implementation without the need for precompiling // instructions. app.RunWhenOnBrowser() // Finally, launching the server that serves the app is done by using the Go // standard HTTP package. // // The Handler is an HTTP handler that serves the client and all its // required resources to make it work into a web browser. Here it is // configured to handle requests with a path that starts with "/". http.Handle("/", &app.Handler{ Name: "Hello", Description: "An Hello World! example", }) if err := http.ListenAndServe(":8000", nil); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Load CLI and Environment Configuration Source: https://github.com/maxence-charriere/go-app/blob/master/pkg/cli/README.md Instantiate your configuration struct, potentially with default values. Register it with the CLI package, providing a program description and the configuration struct. Finally, call `cli.Load()` to populate the struct from flags and environment variables. ```go func main() { cfg := config{ Int: 42, // Set 42 as default value for Int field. } // Registers the config. cli.Register(). Help("A demo cli program"). Options(&cfg) cli.Load() // Stores corresponding cli and env into cfg. fmt.Println(cfg) } ``` -------------------------------- ### Get Input Value in Event Handler Source: https://github.com/maxence-charriere/go-app/blob/master/docs/web/documents/js.md Retrieve the current value of an input element within an event handler. The JSSrc() method provides access to the source element, allowing you to get its 'value' property. ```go func (f *foo) onInputChange(ctx app.Context, e app.Event) { v := ctx.JSSrc().Get("value").String() } ``` -------------------------------- ### OnKeyDown Source: https://github.com/maxence-charriere/go-app/blob/master/docs/web/documents/reference.html Executes a handler when a user starts pressing a key. ```APIDOC ## OnKeyDown ### Description Executes a handler when a user starts pressing a key. ### Method Not applicable (SDK method) ### Parameters - **h** (EventHandler) - Required - The event handler to execute. - **options** (...EventOption) - Optional - Options to configure the event handler. ``` -------------------------------- ### Get Error Tag Source: https://github.com/maxence-charriere/go-app/blob/master/pkg/errors/README.md Retrieve a specific tag value from an error. ```go var err error foo := errors.Tag(err, "foo") ``` -------------------------------- ### Get Error Type Source: https://github.com/maxence-charriere/go-app/blob/master/pkg/errors/README.md Retrieve the custom type associated with an error. ```go var err error t := errors.Type(err) ``` -------------------------------- ### Initialize Go-app Handler Source: https://github.com/maxence-charriere/go-app/wiki/HTTP-Handler Initialize the app handler with application metadata, icon, keywords, theme, styles, and version. This sets up the basic configuration for serving the PWA. ```go h := &app.Handler{ Name: "Luck", Author: "Maxence Charriere", Description: "Lottery numbers generator.", Icon: app.Icon{ Default: "/web/icon.png", }, Keywords: []string{ "EuroMillions", "MEGA Millions", "Powerball", }, ThemeColor: "#000000", BackgroundColor: "#000000", Styles: []string{ "/web/luck.css", }, Version: "wIKiverSiON", } ``` -------------------------------- ### OnKeyDown Source: https://github.com/maxence-charriere/go-app/blob/master/docs/web/documents/reference.html Executes the specified handler when a user starts pressing a key. ```APIDOC ## OnKeyDown ### Description Executes the specified handler when a user starts pressing a key. ### Method Not Applicable (SDK Method) ### Endpoint Not Applicable (SDK Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response Returns the HTMLIFrame element to allow for chaining. #### Response Example None ``` -------------------------------- ### OnKeyDown Source: https://github.com/maxence-charriere/go-app/blob/master/docs/web/documents/reference.html Executes the specified handler when a user starts pressing a key. ```APIDOC ## func OnKeyDown ### Description Executes the specified handler when a user starts pressing a key. ### Method Signature OnKeyDown(h EventHandler, options ...EventOption) HTMLDataList ``` -------------------------------- ### Set State Source: https://github.com/maxence-charriere/go-app/blob/master/docs/web/documents/states.md Handles the 'greet' action by setting a state named 'greet-name' with the provided string value. ```go func handleGreet(ctx app.Context, a app.Action) { name, ok := a.Value.(string) if !ok { return } // Setting a state named "greet-name" with the name value. ctx.SetState("greet-name", name) } ``` -------------------------------- ### Navigate to URL (V8) Source: https://github.com/maxence-charriere/go-app/blob/master/docs/web/documents/v7-to-v8.md Navigating to another page is now a Context method. ```go func (ctx Context) Navigate(rawURL string) ``` -------------------------------- ### OnKeyDown Source: https://github.com/maxence-charriere/go-app/blob/master/docs/web/documents/reference.html Executes the specified handler when a user starts pressing a key. ```APIDOC ## func OnKeyDown ### Description Executes the specified handler when a user starts pressing a key. ### Parameters #### Request Body - **h** (EventHandler) - Required - The handler to invoke. - **options** (...EventOption) - Optional - Additional event options. ``` -------------------------------- ### Build Server Binary Source: https://github.com/maxence-charriere/go-app/wiki/Build-and-deploy Build the Go server component using the standard Go build command. This is used to serve the WebAssembly application. ```sh go build ``` -------------------------------- ### OnKeyDown Event Source: https://github.com/maxence-charriere/go-app/blob/master/docs/web/documents/reference.html Executes the specified handler when a user starts pressing a key. ```APIDOC ## OnKeyDown ### Description Executes the specified handler when a user starts pressing a key. ### Method Not Applicable (Go SDK method) ### Endpoint Not Applicable (Go SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response None #### Response Example None ``` -------------------------------- ### OnKeyDown Source: https://github.com/maxence-charriere/go-app/blob/master/docs/web/documents/reference.html Executes the specified handler when a user starts pressing a key. Can be configured with event options. ```APIDOC ## OnKeyDown ### Description Executes the specified handler when a user starts pressing a key. ### Parameters #### Path Parameters - **h** (EventHandler) - Required - The event handler function. - **options** (...EventOption) - Optional - Additional event options. ``` -------------------------------- ### Set State with Persistence and Broadcast Source: https://github.com/maxence-charriere/go-app/blob/master/docs/web/documents/states.md Sets a state named 'greet-name' and persists it to local storage while also broadcasting it to other browser tabs and windows. ```go func handleGreet(ctx app.Context, a app.Action) { name, ok := a.Value.(string) if !ok { return } ctx.SetState("greet-name", name). Persist(). Broadcast(), ) } ``` -------------------------------- ### Get Environment Variable Source: https://github.com/maxence-charriere/go-app/blob/master/docs/web/documents/reference.html Retrieves the value of an environment variable. Returns an empty string if the variable is not set. ```Go func Getenv(k string) string ``` -------------------------------- ### RunWhenOnBrowser Source: https://github.com/maxence-charriere/go-app/blob/master/docs/web/documents/reference.html Starts the application, rendering the component associated with the current URL path, but only when running in a web browser. ```APIDOC ## RunWhenOnBrowser ### Description Starts the app, displaying the component associated with the current URL path. This call is skipped when the program is not run on a web browser. This allows writing client and server-side code without separation or pre-compilation flags. ### Signature func RunWhenOnBrowser() ### Example ```go func main() { // Define app routes. app.Route("/", myComponent{}) app.Route("/other-page", myOtherComponent{}) // Run the application when on a web browser (only executed on client side). app.RunWhenOnBrowser() // Launch the server that serves the app (only executed on server side): http.Handle("/", &app.Handler{Name: "My app"}) http.ListenAndServe(":8080", nil) } ``` ``` -------------------------------- ### Default Web Directory Structure Source: https://github.com/maxence-charriere/go-app/blob/master/docs/web/documents/static-resources.md Illustrates the default directory structure for static resources, with the 'web' directory located next to the server binary. ```bash . ├── ... # Other source files. ├── hello # Server binary. └── web # Web directory. └── ... # Static resources. ``` -------------------------------- ### Get State Value Source: https://github.com/maxence-charriere/go-app/blob/master/docs/web/documents/states.md Retrieves the current value of the 'greet-name' state and stores it in the 'name' string variable without setting up an observation. ```go func handleGreet(ctx app.Context, a app.Action) { var name string ctx.GetState("greet-name", &name) // ... } ``` -------------------------------- ### Component Creation with app.Compo Source: https://github.com/maxence-charriere/go-app/wiki/Components Demonstrates how to create a new component by embedding the app.Compo struct. This is the fundamental step for defining a reusable UI piece. ```go type hello struct { app.Compo // <-- The base component implementation name string } ``` -------------------------------- ### Get Current Notification Permission Source: https://github.com/maxence-charriere/go-app/blob/master/docs/web/documents/notifications.md Retrieves the current notification permission status. This is useful for determining whether to prompt the user for permission. ```go type foo struct { app.Compo notificationPermission app.NotificationPermission } func (f *foo) OnMount(ctx app.Context) { f.notificationPermission = ctx.Notifications().Permission() } ``` -------------------------------- ### Create Basic Action Source: https://github.com/maxence-charriere/go-app/blob/master/docs/web/documents/actions.md Creates a new action with a given name. Use this when no specific data needs to be passed. ```go func (h *hello) onInputChange(ctx app.Context, e app.Event) { ctx.NewAction("greet") } ``` -------------------------------- ### Prerendered HTML Output Source: https://github.com/maxence-charriere/go-app/blob/master/docs/web/documents/seo.md Example of the HTML output generated by a prerendered go-app component. This static HTML is what search engines will crawl. ```html
Loading...