Home > Software design >  Is it possible to call a Go method in an HTML file?
Is it possible to call a Go method in an HTML file?

Time:10-01

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 <script type = "text/javascript" src="function.js"></script> 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

CodePudding user response:

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.

  • Related