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

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

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

  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "net/http"
  6. "syscall/js" // 我无法使用syscall/js
  7. )
  8. func main() {
  9. fmt.Println("Go Web Assembly")
  10. js.Global().Set("getData", getData)
  11. }
  12. func getData(string, error) {
  13. resp, err := http.Get("https://jsonplaceholder.typicode.com/posts")
  14. if err != nil {
  15. return
  16. }
  17. // We Read the response body on the line below.
  18. body, err := ioutil.ReadAll(resp.Body)
  19. if err != nil {
  20. return
  21. }
  22. // Convert the body to type string
  23. sb := string(body)
  24. return sb
  25. }
英文:

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

  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "net/http"
  6. "syscall/js" // I can't use syscall/js
  7. )
  8. func main() {
  9. fmt.Println("Go Web Assembly")
  10. js.Global().Set("getData", getData)
  11. }
  12. func getData(string, error) {
  13. resp, err := http.Get("https://jsonplaceholder.typicode.com/posts")
  14. if err != nil {
  15. return
  16. }
  17. // We Read the response body on the line below.
  18. body, err := ioutil.ReadAll(resp.Body)
  19. if err != nil {
  20. return
  21. }
  22. // Convert the body to type string
  23. sb := string(body)
  24. return sb
  25. }

答案1

得分: 9

syscall/js包确实有一个构建约束:

  1. // +build js,wasm

你需要使用正确的GOOSGOARCH选项来构建程序(参考链接:https://github.com/golang/go/wiki/WebAssembly#getting-started):

  1. GOOS=js GOARCH=wasm go build -o main.wasm
英文:

The syscall/js package has indeed a build constraint:

  1. // +build js,wasm

You need to build the program with the correct GOOS and GOARCH options:

  1. 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:

确定