F
F
Furylon2022-04-13 21:37:12
JavaScript
Furylon, 2022-04-13 21:37:12

Execute/call function from Go file on click on html button?

Hello. I am learning how to create web applications in Golang.
By default, html buttons can perform JS functions.
How to call a function from Go code when a user clicks a button on a website?
Of course, first rummaged through the internet. It all comes down to AJAX or Rest api. But there is no information on the question asked. Basically everything about creating and testing the server and just water about the possibilities. No specifics.

Those. for the sake of accuracy of the example:
in main.go, in the page function, there is a conditional function foo() that processes the data on the page and outputs it.
There is a button in html that, when clicked, executes this function foo()

A bunch of answers are abstract: use AJAX or Rest API. I did not find any materials on specific tasks using these resources. Only the general plan of work.
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Mamonov, 2022-04-13
@Furylon

Your algorithm will be something like this...
When you click on the button, a function will be called (the button's onClick event handler).
In this function, you will make an HTTP AJAX request to your server where your Go software is running.
In main.go, you start an HTTP server that will accept the request from your JavaScript function, process it, and respond.
Let's analyze the simplest option with the GET method to make it easier for you to test.
On the server (your computer), run main.go with something like this

package main

import (
    "fmt"
    "net/http"
)

func helloHandler(w http.ResponseWriter, req *http.Request) {
    fmt.Fprintf(w, "hello\n")
}

func main() {
    http.HandleFunc("/hello", helloHandler)

    http.ListenAndServe(":8081", nil)
}

This service will listen on port 8081 of any IP address on the server where it will run.
Suppose you are testing on your own computer, in this case, to test, you need to open the url in the browser ` 127.0.0.1:8081/hello `
After that, you should see in the response just the text: "hello".
When this stage is completed, you can move on to calling this URL already from JavaScript.
To do this, you can use what is more familiar to you, if this is not the case, you can use this example.
const req = new XMLHttpRequest();
  const url='http://127.0.0.1:8081/hello';
  req.open("GET", url);
  req.send();
  req.onreadystatechange=(e)=>{
    console.log(req.responseText)
  }

PS: If it is not clear or something does not work out - write, I will help you figure it out.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question