在HTML文件中调用Go方法是否可能?

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

Is it possible to call a Go method in an HTML file?

问题

我有一个用HTML编写的网页,上面有一个按钮。当点击这个按钮时,理论上应该调用一个位于另一个用Go编写的文件中的函数。

然而,在尝试实现这个功能后,我开始怀疑是否可能。我阅读了一些相关文档,但对于如何在HTML中导入这个函数感到困惑,因为通常的<script type="text/javascript" src="function.js"></script>并没有起作用,我猜测是由于类型错误。根据我所了解的,text/javascript是一个独特的类型,没有与之等价的text/go。是否有人有任何参考资料或链接,可以帮助我指导如何在我的HTML页面上点击按钮时调用我在.go文件中编写的方法?

以下是程序结构:

程序
-- home.html
-- settings.go
英文:

I have a webpage written in html which has a button on it. When this button is clicked, it should hypothetically call on a function located in a separate file which is written in Go.

However, after trying to implement this, I am starting to doubt whether this is possible at all. I've read some documentation about this, but am confused as to how I would import this function in html as the normal &lt;script type = &quot;text/javascript&quot; src=&quot;function.js&quot;&gt;&lt;/script&gt; isn't quite working from what I assume is due to the type error. From what I have been able to find text/javascript is a unique type and there is no text/go equivalent. Does anyone have any references or links which would help direct me in the right direction as to how I could go about calling the method I've written in my .go file when a button is clicked on my html page?

Here is the program structure below:

Program
-- home.html
-- settings.go

答案1

得分: 2

你所描述的情况是不可能的,原因有几个。

Go是一种编译语言。与JS不同,Go程序是二进制文件,所以不需要源代码,而是需要二进制文件。这个概念由Web Assembly实现,你可以使用Go构建Web Assembly。但是,它在分发之前会被编译。

Javascript是一种独特的语言,它是HTML浏览器环境的主要组成部分,并且与浏览器有良好的集成。其他语言如Go、Python等都没有这样的特性。

从技术上讲,将任何语言转换为Javascript是可能的,但我建议暂时不要涉及这种把戏。

但是你可以在Go中编写程序,然后通过浏览器与之交互。你的Javascript代码可以向提供HTTP服务的Go程序发送HTTP请求。你需要决定如何交换数据。

英文:

What you're describing definitely isn't possible, for a few reasons.

Go is a compiled language. Unlike JS, Go programs are binaries. So their source wouldn't be needed, a binary would. This concept is implemented by Web Assembly and you can use go to build web assembly. But again, it is compiled before being distributed.

Javascript is unique in being a primary component of html browser environment and enjoys integration with the browser. No other languages do this: not Go, python, etc.

It's technically possible to turn any language into Javascript, but I'd advise leaving such shenanigans alone for now.

But you can write a program in Go and then interact with it from the browser. Your Javascript would make http requests to a Go program serving http. You'd be responsible for deciding how data was exchanged.

huangapple
  • 本文由 发表于 2021年10月1日 06:30:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/69399445.html
匿名

发表评论

匿名网友

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

确定