温馨提示×

golang后端怎么给前端传数据

小亿
111
2024-01-19 15:39:29
栏目: 编程语言

Go语言的后端可以使用以下几种方式给前端传递数据:

  1. JSON格式: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)
}
  1. HTML模板:Go语言中可以使用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)
}
  1. WebSocket:Go语言中可以使用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)
}

以上是几种常见的方式,根据具体需求选择适合的传输方式。

0