导入 syscall/js:构建约束排除了 /usr/local/go/src/syscall 中的所有 Go 文件。

huangapple go评论94阅读模式
英文:

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

你需要使用正确的GOOSGOARCH选项来构建程序(参考链接: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

huangapple
  • 本文由 发表于 2021年8月16日 14:13:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/68798120.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定