我试图通过将 Go 函数转换为 Web 程序集来在 javascript 中使用 Go api 调用函数。为此,我尝试导入,syscall/js但它会引发以下错误:
导入 syscall/js:构建约束排除 /usr/local/go/src/syscall/js 中的所有 Go 文件
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
}
Run Code Online (Sandbox Code Playgroud)
bla*_*een 11
该syscall/js包确实有构建约束:
// +build js,wasm
Run Code Online (Sandbox Code Playgroud)
或者使用现代构建约束语法:
//go:build js && wasm
Run Code Online (Sandbox Code Playgroud)
您需要使用正确GOOS的GOARCH选项来构建程序:
GOOS=js GOARCH=wasm go build -o main.wasm
Run Code Online (Sandbox Code Playgroud)