首页 > 解决方案 > 导入 syscall/js:构建约束排除 /usr/local/go/src/syscall 中的所有 Go 文件

问题描述

我正在尝试通过将 Go 函数转换为 Web 程序集来在 javascript 中使用 Go api-call 函数。为此,我正在尝试导入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
}

标签: gowebassembly

解决方案


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

// +build js,wasm

您需要使用正确的GOOSGOARCH选项构建程序:

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

推荐阅读