Dhanush
Dhanush

Reputation: 111

imports syscall/js: build constraints exclude all Go files in /usr/local/go/src/syscall

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
}

Upvotes: 8

Views: 6045

Answers (1)

blackgreen
blackgreen

Reputation: 44665

The syscall/js package has indeed a build constraint:

// +build js,wasm

Or with the modern build constraint syntax:

//go: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

Upvotes: 14

Related Questions