Go语言的后端可以使用以下几种方式给前端传递数据:
encoding/json
包来将数据转换成JSON格式,然后通过HTTP响应发送给前端。前端可以使用JavaScript的JSON.parse()
方法将JSON字符串转换为对象。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)
}
html/template
包来渲染HTML模板,并将数据传递给模板。前端可以通过模板引擎将数据渲染到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)
}
gorilla/websocket
包来实现WebSocket通信,实时传递数据给前端。前端可以使用WebSocket
对象接收后端发送的数据。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)
}
以上是几种常见的方式,根据具体需求选择适合的传输方式。