[Solved] need to send golang data to html by button click


You probably put very little effort into figuring this out. Though I am bored so I decided to help you out. Here is your backend:

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"
    "time"
)

type Response struct {
    CurrentTime string
}

func main() {
    http.Handle("/", http.FileServer(http.Dir("web")))

    http.HandleFunc("/get-time", func(rw http.ResponseWriter, r *http.Request) {
        ctime := Response{
            CurrentTime: time.Now().Format(time.RFC3339),
        }
        byteArray, err := json.Marshal(ctime)
        if err != nil {
            fmt.Println(err)
        }
        rw.Write(byteArray)
    })

    if err := http.ListenAndServe(":5000", nil); err != nil {
        log.Fatal(err)
    }
}

And you also need frontend located in (web/index.html):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button id="gt">get time</button>
    <div id="res"></div>
    <script>
        document.getElementById("gt").onclick = async (e) => {
            var req = await fetch("\get-time").then(r => r.json())
            document.getElementById("res").innerHTML = req.CurrentTime
        }
    </script>
</body>
</html>

2

solved need to send golang data to html by button click