Go語言的后端可以使用以下幾種方式給前端傳遞數(shù)據(jù):
encoding/json
包來將數(shù)據(jù)轉(zhuǎn)換成JSON格式,然后通過HTTP響應(yīng)發(fā)送給前端。前端可以使用JavaScript的JSON.parse()
方法將JSON字符串轉(zhuǎn)換為對象。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模板,并將數(shù)據(jù)傳遞給模板。前端可以通過模板引擎將數(shù)據(jù)渲染到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
包來實現(xiàn)WebSocket通信,實時傳遞數(shù)據(jù)給前端。前端可以使用WebSocket
對象接收后端發(fā)送的數(shù)據(jù)。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)
}
以上是幾種常見的方式,根據(jù)具體需求選擇適合的傳輸方式。