Good to know: I recommand to install wasmbrowsertest for live testings
Minimal code for a WebAssembly project
You MUST always include a waiting channel at the end of the main function. If you're not including this channel, the wasm just load, exec and stopped. If you web app export some functions, handle events , all this functional code is unloaded and can't be used.
Init your project with the namespace of your choice
go mod init hogosuruworld
Add the hogosuru framework:
GOOS=js GOARCH=wasm go get github.com/realPy/hogosuru@latest
Create your main.go with content:
Launch main.go
It open a chrome instance with content
Let's take a closer look at the code
Your main must always call first the initialisation frameworks
Get the current document. If an error occurs AssertErr can handle this error and log in console. It's recommend to use AssertErr to handle error, AssertErr can be hook in a future version to a bug tracker like Sentry.
Get the current body in the document
Create dynamically the htmlelement h1
Set the text between the <h1></h1>
Append the h1 to the end of the node contains in body
Infinite waiting with a channel
If a struct{} is sent to the channel, the wasm is unloaded and all current work and function are unloaded. This function can be used to reloaded a new wasm (for example) and you must ensure there is no work in progress.
package main
import (
"github.com/realPy/hogosuru"
"github.com/realPy/hogosuru/document"
"github.com/realPy/hogosuru/htmlheadingelement"
)
func main() {
hogosuru.Init()
//we get the current document if an error occur the err is draw to the console thank to AssertErr
if doc, err := document.New(); hogosuru.AssertErr(err) {
//we get the body of the document if an error occur the err is draw to the console thank to AssertErr
if body, err := doc.Body(); hogosuru.AssertErr(err) {
//now we create dynamiclly the h1 element
if h1, err := htmlheadingelement.NewH1(doc); hogosuru.AssertErr(err) {
//We set the text content with Hello World
h1.SetTextContent("Hello world")
// and append to the body
body.AppendChild(h1.Node)
}
}
}
ch := make(chan struct{})
<-ch
}
WASM_HEADLESS=off GOOS=js GOARCH=wasm go run main.go
hogosuru.Init()
if doc, err := document.New(); hogosuru.AssertErr(err) {
if body, err := doc.Body(); hogosuru.AssertErr(err) {
if h1, err := htmlheadingelement.NewH1(doc); hogosuru.AssertErr(err) {