Go WASM Fetch Example - Go-wasm Typing CST Test
Loading…
Go WASM Fetch Example — Go-wasm Code
Uses fetch to get data from an API and displays it.
# go/demo/fetch.go
package main
import (
"syscall/js"
)
func main() {
doc := js.Global().Get("document")
p := doc.Call("createElement", "p")
doc.Get("body").Call("appendChild", p)
js.Global().Call("fetch", "https://api.github.com")
.Call("then", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
response := args[0]
response.Call("text").Call("then", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
p.Set("innerHTML", args[0].String())
return nil
}))
return nil
}))
select{}
}Go-wasm Language Guide
Go-WASM refers to compiling Go (Golang) programs to WebAssembly, allowing Go code to run in the browser. It enables developers to leverage Go's concurrency model and standard library on the client-side, interacting with JavaScript and the DOM.
Primary Use Cases
- ▸Porting existing Go libraries to run in the browser
- ▸Computational-heavy browser tasks (e.g., data processing, simulations)
- ▸SPAs with Go backend logic mirrored on the client
- ▸Browser games leveraging Go routines
- ▸Replacing JavaScript for Go-centric full-stack applications
Notable Features
- ▸Compile Go code to WebAssembly for browser execution
- ▸Interoperability with JavaScript using `syscall/js`
- ▸Supports Go goroutines and channels (with some browser runtime constraints)
- ▸Leverages Go's standard library in the browser
- ▸Works with modern browsers supporting WebAssembly
Origin & Creator
Go-WASM is maintained by the Go project team at Google, introduced as part of Go 1.11 with WebAssembly as a supported compilation target.
Industrial Note
Go-WASM is ideal for Go developers who want to run Go code in the browser without rewriting logic in JavaScript or TypeScript, especially for apps needing Go's concurrency or existing Go code reuse.