How to pass data from the Golang backend to the frontend?

There are several ways in which the backend of Go language can transfer data to the frontend.

  1. JSON encoding
  2. convert JSON data into a JavaScript object
import (
    "encoding/json"
    "net/http"
)

type Person struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        person := Person{
            Name: "John",
            Age:  25,
        }
        json.NewEncoder(w).Encode(person)
    })

    http.ListenAndServe(":8080", nil)
}
  1. template using html
import (
    "html/template"
    "net/http"
)

type Person struct {
    Name string
    Age  int
}

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        person := Person{
            Name: "John",
            Age:  25,
        }
        tmpl, _ := template.ParseFiles("index.html")
        tmpl.Execute(w, person)
    })

    http.ListenAndServe(":8080", nil)
}
  1. WebSocket library for the programming language Go.
  2. A communication protocol that enables real-time two-way interaction between a server and a client over a single, long-lived connection.
import (
    "net/http"
    "github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
    ReadBufferSize:  1024,
    WriteBufferSize: 1024,
}

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        conn, _ := upgrader.Upgrade(w, r, nil)
        for {
            _, message, _ := conn.ReadMessage()
            conn.WriteMessage(1, message)
        }
    })

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

These are several common options, choose the appropriate method based on specific needs.

bannerAds