Go言語のバックエンドは、フロントエンドにデータを渡す方法は何ですか?

Go言語のバックエンドでは、フロントエンドにデータを渡すために複数の方法が利用できます。

  1. エンコーディング/json
  2. JSON.parse() を使用する
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/templateは、HTMLテンプレートを使って動的にWebページを生成するためのGo言語のパッケージです。
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. ゴリラ/ウェブソケット
  2. ウェブソケット
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)
}

これらはよく使われるいくつかの方法です。具体的なニーズに応じて適切な転送方法を選択してください。

bannerAds