英文:
imports syscall/js: build constraints exclude all Go files in /usr/local/go/src/syscall
问题
我正在尝试通过将Go函数转换为WebAssembly,在JavaScript中使用Go的API调用函数。为了做到这一点,我尝试导入syscall/js
,但是它抛出以下错误:
imports syscall/js: build constraints exclude all Go files in /usr/local/go/src/syscall/js
package main
import (
"fmt"
"io/ioutil"
"net/http"
"syscall/js" // 我无法使用syscall/js
)
func main() {
fmt.Println("Go Web Assembly")
js.Global().Set("getData", getData)
}
func getData(string, error) {
resp, err := http.Get("https://jsonplaceholder.typicode.com/posts")
if err != nil {
return
}
// We Read the response body on the line below.
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
// Convert the body to type string
sb := string(body)
return sb
}
英文:
I am trying to use Go api-call function in javascript by converting the Go function into web assembly. To do that I am trying to import syscall/js
but it throws the following error:
> imports syscall/js: build constraints exclude all Go files in /usr/local/go/src/syscall/js
package main
import (
"fmt"
"io/ioutil"
"net/http"
"syscall/js" // I can't use syscall/js
)
func main() {
fmt.Println("Go Web Assembly")
js.Global().Set("getData", getData)
}
func getData(string, error) {
resp, err := http.Get("https://jsonplaceholder.typicode.com/posts")
if err != nil {
return
}
// We Read the response body on the line below.
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
// Convert the body to type string
sb := string(body)
return sb
}
答案1
得分: 9
syscall/js
包确实有一个构建约束:
// +build js,wasm
你需要使用正确的GOOS
和GOARCH
选项来构建程序(参考链接:https://github.com/golang/go/wiki/WebAssembly#getting-started):
GOOS=js GOARCH=wasm go build -o main.wasm
英文:
The syscall/js
package has indeed a build constraint:
// +build js,wasm
You need to build the program with the correct GOOS
and GOARCH
options:
GOOS=js GOARCH=wasm go build -o main.wasm
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论