【问题标题】:Go Web Assembly cannot Click Run when enter http://localhost:8080/wasm_exec.htmlGo Web Assembly 在输入 http://localhost:8080/wasm_exec.html 时无法点击运行
【发布时间】:2019-12-07 07:12:04
【问题描述】:

我是 stackoverflow 和 golang Web 程序集的新手

我很困惑这个问题:我写了一个测试代码

main.go

package main

func main(){
    println("hello world")
}

我已经生成了 main.wasm 并将 wasm_exec.js 和 wasm_exec.html 导入到工作目录

我也写了一个网络服务器

package main

import (
    "flag"
    "log"
    "net/http"
)

var (
    listen = flag.String("listen", ":8080", "listen address")
    dir    = flag.String("dir", ".", "directory to serve")
)

func main() {
    flag.Parse()
    log.Printf("listening on %q...", *listen)
    err := http.ListenAndServe(*listen, http.FileServer(http.Dir(*dir)))
    log.Fatalln(err)
}

我用 Chrome 输入http://localhost:8080/wasm_exec.html

根据网上的资料,有一个“运行”按钮,可以点击。

但是,实际上我不能点击这个按钮

我真的很困惑

这是我关于 stackoverflow 的第一个问题。

抱歉英语不好

【问题讨论】:

  • 检查您的 HTML 代码。可能默认情况下禁用了用于添加“运行”按钮的 HTML 代码,并且您没有从 Go 代码中启用它。例如。 。您也可以删除 disabled 关键字。

标签: go webassembly


【解决方案1】:

一步一步 Hello World 来自 Go WebAssembly:
web/main.go 文件:

package main

import (
    "log"
    "net/http"
)

func main() {
    http.Handle("/", http.FileServer(http.Dir(".")))
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

main.go文件:

package main

import "fmt"

func main() {
    fmt.Println("Hello World")
}

在 Linux 终端中运行以下命令(对于 Windows 操作系统,将 cp 替换为 copy,将 $GOROOT 替换为 %GOROOT%):

GOOS=js GOARCH=wasm go build -o test.wasm
cp $GOROOT/misc/wasm/wasm_exec.html ./
cp $GOROOT/misc/wasm/wasm_exec.js ./

go run web/main.go

打开http://127.0.0.1:8080/wasm_exec.html

现在在浏览器中右键单击浏览器,然后选择Inspect,然后选择Console 选项卡,现在该单击Run 按钮,然后您将在浏览器控制台中看到Hello World。

【讨论】:

  • 当我在 github(wasmup/go109calc) 上看到您的代码时,我遇到了另一个问题。我想看看它是如何工作的,所以我在我的 Goland 中复制了你的代码。但是当我运行它时,浏览器控制台检测到错误-----Uncaught (in promise) LinkError: WebAssembly.instantiate(): Import #18 module="go" function="syscall/js.copyBytesToJS" 错误:函数导入需要一个可调用的
  • 当我点击 Factorial 和 isPrime 时,它​​还会检测到错误 Uncaught ReferenceError: isPrime is not defined at HTMLInputElement.onclick ((index):32)
  • 但它确实适用于您的 github html。所以我不知道为什么。我的操作系统是 windows 10 在此先感谢
  • 你不应该以这种方式运行 WebAssembly 代码,就像这个答案一样,首先在终端中运行:cd goserve && go install && cd .. 然后运行goserve 等于上面的go run web/main.go 然后你很好去打开http://127.0.0.1:8080/
  • 我不知道如何使用 Markdown 很抱歉。我制作 index.html main.go main.js main.css test.wasm(由 main.go 生成) wasm_exec.js web .go(也就是你说的web/main.go)在同一个目录然后我运行web.go 然后我打开localhost:8080
猜你喜欢
  • 2017-07-21
  • 2016-10-05
  • 2013-09-29
  • 2011-01-31
  • 2015-05-20
  • 2017-09-07
  • 2015-09-20
  • 2017-10-08
  • 2016-10-13
相关资源
最近更新 更多