溫馨提示×

golang后端怎么給前端傳數(shù)據(jù)

小億
148
2024-01-19 15:39:29
欄目: 編程語言

Go語言的后端可以使用以下幾種方式給前端傳遞數(shù)據(jù):

  1. JSON格式:Go語言中可以使用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)
}
  1. HTML模板:Go語言中可以使用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)
}
  1. WebSocket:Go語言中可以使用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ù)具體需求選擇適合的傳輸方式。

0