Did someone know how i can call a Golang Methode (func stop(){) from JavaScript?
Thanks, Leon
Did someone know how i can call a Golang Methode (func stop(){) from JavaScript?
Thanks, Leon
Hey @Leon_Merten, you could always use ajax to call back to a server running Go.
Here’s an example:
(P.S. You don’t need to run the index.html
file on the Go server for it to work like in this example, but I prefer to keep everything running together)
index.html
:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Call Go</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#callGo").on('click', function() {
$.ajax({
url: "http://localhost:9000/callme",
method: "GET",
success: function(data) {
$("#response").html(data);
},
});
});
});
</script>
</head>
<body>
<button id="callGo" type="submit">Call Go Code</button>
<div id="response"></div>
</body>
</html>
main.go
:
package main
import (
"fmt"
"html/template"
"log"
"net/http"
)
// Load the index.html template.
var tmpl = template.Must(template.New("tmpl").ParseFiles("index.html"))
func main() {
// Serve / with the index.html file.
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if err := tmpl.ExecuteTemplate(w, "index.html", nil); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
// Serve /callme with a text response.
http.HandleFunc("/callme", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "You called me!")
})
// Start the server at http://localhost:9000
log.Fatal(http.ListenAndServe(":9000", nil))
}
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.