在JavaScript中如何执行Golang函数

在JavaScript中如何执行Golang函数 我有一个这样的函数:

func Hello(){
    log.Printf("Hello world")
}

我想要的只是当用户按下我模板上的一个按钮时,它能执行 Go 中的 Hello 函数。

就像这样:

function SubmitFunction() {
    //EXECUTE GO FUNCTION
    document.getElementById("myForm").submit();
}
5 回复

是的,我就像在我的电脑上运行一个服务器,并且我想执行一个函数,它具体做什么并不重要。我写 log.Printf 只是举个例子。

func main() {
    fmt.Println("hello world")
}

更多关于在JavaScript中如何执行Golang函数的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


听起来您是想向一个Go API提交表单?我建议您查看 https://gowebexamples.com/ 作为起点。特别是其中的表单部分,它演示了如何实现我认为您所询问的功能。

我想要的只是当用户在我的模板上按下一个按钮时,它能执行 Go 中的 Hello 函数。

你能说得更具体一点吗?你是在运行一个用 Go 编写的 Web 服务,想要执行一个模板并将结果返回给用户,还是实际上在浏览器中运行 Go(例如使用 WASM),并希望通过从 WASM 导出到 JavaScript 来调用该函数?

我想要的只是当用户在我的模板上按下一个按钮时,它能执行 Go 中的 Hello 函数

我通过向 Go Web 服务器添加一个端点来实现这一点。不是打开一个 HTML 页面,而是触发一个函数。

switch path {
  case "function":
    hello(w, r)
  case "": 
    tpl.ExecuteTemplate(w, "home.html", url)
  default:
    tpl.ExecuteTemplate(w, page, url)
}

在JavaScript中直接执行Go函数是不可能的,因为JavaScript运行在浏览器中,而Go运行在服务器端。你需要通过HTTP请求来触发服务器端的Go函数。以下是几种实现方式:

1. 使用表单提交(最简单的方式)

// Go后端代码
package main

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

func helloHandler(w http.ResponseWriter, r *http.Request) {
    if r.Method == "POST" {
        log.Printf("Hello world")
        fmt.Fprintf(w, "Hello function executed")
    }
}

func main() {
    http.HandleFunc("/hello", helloHandler)
    http.ListenAndServe(":8080", nil)
}
<!-- HTML模板 -->
<form id="myForm" action="/hello" method="POST">
    <button type="submit">执行Go函数</button>
</form>

2. 使用Fetch API(推荐方式)

// JavaScript代码
async function SubmitFunction() {
    try {
        const response = await fetch('/hello', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            }
        });
        
        if (response.ok) {
            const result = await response.text();
            console.log(result);
            // 如果需要,可以在这里提交表单
            document.getElementById("myForm").submit();
        }
    } catch (error) {
        console.error('Error:', error);
    }
}

3. 使用XMLHttpRequest

function SubmitFunction() {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "/hello", true);
    xhr.setRequestHeader("Content-Type", "application/json");
    
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
            console.log("Go函数执行成功");
            document.getElementById("myForm").submit();
        }
    };
    
    xhr.send();
}

4. 完整示例:Go后端 + HTML/JS前端

// main.go
package main

import (
    "fmt"
    "log"
    "net/http"
    "text/template"
)

func helloHandler(w http.ResponseWriter, r *http.Request) {
    if r.Method == "POST" {
        log.Printf("Hello world")
        fmt.Fprintf(w, `{"status": "success", "message": "Hello function executed"}`)
    }
}

func homeHandler(w http.ResponseWriter, r *http.Request) {
    tmpl := template.Must(template.ParseFiles("index.html"))
    tmpl.Execute(w, nil)
}

func main() {
    http.HandleFunc("/", homeHandler)
    http.HandleFunc("/hello", helloHandler)
    log.Println("服务器启动在 http://localhost:8080")
    http.ListenAndServe(":8080", nil)
}
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
    <title>执行Go函数示例</title>
</head>
<body>
    <form id="myForm" action="/submit" method="POST">
        <!-- 表单内容 -->
    </form>
    
    <button onclick="SubmitFunction()">执行Go函数并提交表单</button>
    
    <script>
    async function SubmitFunction() {
        // 先执行Go函数
        const response = await fetch('/hello', {
            method: 'POST'
        });
        
        if (response.ok) {
            const data = await response.json();
            console.log(data.message);
            // 然后提交表单
            document.getElementById("myForm").submit();
        }
    }
    </script>
</body>
</html>

运行Go服务器后,当用户点击按钮时,会先向/hello端点发送POST请求执行Go函数,然后提交表单。

回到顶部