pigfox
pigfox

Reputation: 1401

build constraints exclude all Go files

This is my first attempt to do Webassembly and I've bumped into an issue.

I'm using: go version go1.14.3 linux/amd64

The code compiles properly with:

GOARCH=wasm GOOS=js go build -o lib.wasm main.go

When I do: go run main.go

I get the following error:

main.go:8:2: build constraints exclude all Go files in /usr/local/go/src/syscall/js

Any ideas how to solve this?

package main

import (
    "flag"
    "log"
    "net/http"
    "strconv"
    "syscall/js"
)

var (
    listen = flag.String("listen", ":8080", "listen address")
    dir    = flag.String("dir", ".", "directory to serve")
)

func add(i []js.Value) {
    value1 := js.Global().Get("document").Call("getElementById", i[0].String()).Get("value").String()
    value2 := js.Global().Get("document").Call("getElementById", i[1].String()).Get("value").String()

    int1, _ := strconv.Atoi(value1)
    int2, _ := strconv.Atoi(value2)

    js.Global().Get("document").Call("getElementById", i[2].String()).Set("value", int1+int2)
}


func subtract(i []js.Value) {
    value1 := js.Global().Get("document").Call("getElementById", i[0].String()).Get("value").String()
    value2 := js.Global().Get("document").Call("getElementById", i[1].String()).Get("value").String()

    int1, _ := strconv.Atoi(value1)
    int2, _ := strconv.Atoi(value2)

    js.Global().Get("document").Call("getElementById", i[2].String()).Set("value", int1-int2)
}

func registerCallbacks() {
    js.Global().Set("add", new(func()))
    js.Global().Set("subtract", new(func()))
    //js.Global().Set("subtract", js.NewCallback(subtract))

    //cannot use add (type func([]js.Value)) as type func(js.Value, []js.Value) interface {} in argument to js.FuncOf
    //js.Global().Set("add", js.FuncOf(add))
    //js.Global().Set("subtract", js.FuncOf(subtract))
}

func main() {
    flag.Parse()
    log.Printf("listening on %q...", *listen)
    log.Fatal(http.ListenAndServe(*listen, http.FileServer(http.Dir(*dir))))
    c := make(chan struct{}, 0)

    println("WASM Go Initialized")
    // register functions
    registerCallbacks()
    <-c
}

Upvotes: 2

Views: 9745

Answers (1)

blami
blami

Reputation: 7411

You can't use go run with GOARCH=wasm; go run executes the built binary and because it is not OS native binary but wasm it will end up with operating system not understanding format of it.

Instructions how to execute WebAssembly binaries both directly using wasm_exec.js shim directly and Node.js are written down on WebAssembly wiki page of golang/go repository.

To run tests in browser there is nice Golang package agnivade/wasmbrowsertest.

Upvotes: 4

Related Questions