Created
September 3, 2018 07:21
-
-
Save miguelmota/67d212e8905ae009753e48012476af65 to your computer and use it in GitHub Desktop.
Go (golang) WebAssembly (WASM) hello world example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"syscall/js" | |
) | |
// Add ... | |
func Add(a, b int) int { | |
return a + b | |
} | |
func main() { | |
c := make(chan struct{}, 0) | |
add := func(args []js.Value) { | |
go func() { | |
js.Global().Set("output", js.ValueOf(Add(args[0].Int(), args[1].Int()))) | |
close(c) | |
}() | |
} | |
js.Global().Set("add", js.NewCallback(add)) | |
<-c | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
compile: | |
GOARCH=wasm GOOS=js go build -o test.wasm main.go | |
copy: | |
cp $(go env GOROOT)/misc/wasm/wasm_exec.{html,js} . | |
serve: | |
go run server.go |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"flag" | |
"log" | |
"net/http" | |
"strings" | |
) | |
var ( | |
listen = flag.String("listen", ":8080", "listen address") | |
dir = flag.String("dir", ".", "directory to serve") | |
) | |
func main() { | |
flag.Parse() | |
log.Printf("listening on %q...", *listen) | |
log.Fatal(http.ListenAndServe(*listen, http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { | |
if strings.HasSuffix(req.URL.Path, ".wasm") { | |
resp.Header().Set("content-type", "application/wasm") | |
} | |
http.FileServer(http.Dir(*dir)).ServeHTTP(resp, req) | |
}))) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment