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.
- JSON encoding
- 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)
}
- 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)
}
- WebSocket library for the programming language Go.
- 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.