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)
}
以上是幾種常見的方式,根據具體需求選擇適合的傳輸方式。