1 回答

TA貢獻1951條經驗 獲得超3個贊
盡管 x/net/websocket 連接具有與 io.Reader 中的 Read 方法具有相同簽名的 Read 方法,但該連接不像 io.Reader 那樣工作。使用 bufio.Scanner 包裹時,連接將無法正常工作。
poa.st 端點發送消息流,其中每條消息都是一個 JSON 文檔。使用以下代碼使用Gorilla 包讀取消息:
url := "wss://poa.st/api/v1/streaming/?stream=public"
ws, _, err := websocket.DefaultDialer.Dial(url, nil)
if err != nil {
log.Fatal(err)
}
defer ws.Close()
for {
_, p, err := ws.ReadMessage()
if err != nil {
log.Fatal(err)
}
// p is a []byte containing the JSON document.
fmt.Printf("%s\n", p)
}
Gorilla 包有一個用于解碼 JSON 消息的輔助方法。這是一個如何使用該方法的示例。
url := "wss://poa.st/api/v1/streaming/?stream=public"
ws, _, err := websocket.DefaultDialer.Dial(url, nil)
if err != nil {
log.Fatal(err)
}
defer ws.Close()
for {
// The JSON documents are objects containing two fields,
// the event type and the payload. The payload is a JSON
// document itself.
var e struct {
Event string
Payload string
}
err := ws.ReadJSON(&e)
if err != nil {
log.Fatal(err)
}
// TODO: decode e.Payload based on e.Event
}
- 1 回答
- 0 關注
- 166 瀏覽
添加回答
舉報