使用 golang 和 gorilla websocket 库,为什么 WriteJson return 会出错?
Using golang with the gorilla websocket library, why does WriteJson return an error?
我正在按照此处的说明进行操作:
https://testnet.bitmex.com/app/wsAPI
并且我已经确认以下 Python 实施有效(即我这边没有网络问题等),因为:
python wsdump.py \
wss://testnet.bitmex.com/realtime
> {"op":"subscribe","args":["orderBookL2_25:XBTUSD"]}
结果
{"success":true,"subscribe":"orderBookL2_25:XBTUSD","request":{"op":"subscribe","args":["orderBookL2_25:XBTUSD"]}}
我已经尝试修改大猩猩示例代码来组合一个基本客户端:
package main
import (
"encoding/json"
"flag"
"fmt"
"log"
"net/url"
"os"
"os/signal"
"time"
"github.com/gorilla/websocket"
)
var addr = flag.String("addr", "testnet.bitmex.com", "http service address")
func main() {
flag.Parse()
log.SetFlags(0)
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
u := url.URL{Scheme: "wss", Host: *addr, Path: "/realtime"}
log.Printf("connecting to %s", u.String())
c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
if err != nil {
log.Fatal("dial:", err)
}
defer c.Close()
done := make(chan struct{})
go func() {
defer close(done)
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("read:", err)
return
}
log.Printf("recv: %s", message)
}
}()
type commandStruct struct {
Op string `json:"op"`
Args []string `json:"args"`
}
command := &commandStruct{
Op: "subscribe",
Args: []string{"orderBookL2_25:XBTUSD"}}
json, _ := json.Marshal(command)
stringJSON := string(json)
fmt.Println("JSON:", stringJSON)
connectionErr := c.WriteJSON(stringJSON)
if connectionErr != nil {
log.Println("write:", connectionErr)
}
for {
select {
case <-done:
return
case <-interrupt:
log.Println("interrupt")
// Cleanly close the connection by sending a close message and then
// waiting (with timeout) for the server to close the connection.
err := c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
if err != nil {
log.Println("write close:", err)
return
}
select {
case <-done:
case <-time.After(time.Second):
}
return
}
}
}
我的程序将以下内容打印到控制台:
{"op":"subscribe","args":["orderBookL2_25:XBTUSD"]}
与上面 Python 示例中的 JSON 相同。但随后我收到一条错误消息:
recv: {"status":400,"error":"Unrecognized request. See the docs or send 'help' for more details.","meta":{},"request":"{\"op\":\"subscribe\",\"args\":[\"orderBookL2_25:XBTUSD\"]}"}
为什么我得到不同的结果?
问题是应用程序将值双重编码为 JSON:
对 json.Marshal(command)
的调用将 command
结构编码为 JSON:
{"op":"subscribe","args":["orderBookL2_25:XBTUSD"]}
调用 c.WriteJSON(stringJSON)
将该文本编码为 JSON 并将其写入网络。双重编码的 JSON 是:
"{\"op\":\"subscribe\",\"args\":[\"orderBookL2_25:XBTUSD\"]}"
请改用以下代码:
connectionErr := c.WriteJSON(command)
我知道这是一个有点老的话题,我的回答并没有直接解决操作员提出的问题,但由于我有一个非常相似的问题,我想提出一个稍微不同的解决方案:
下面可以使用WriteMessage更直接的编码,而不是WriteJSON
type commandStruct struct {
Op string `json:"op"`
Args []string `json:"args"`
}
command := &commandStruct{
Op: "subscribe",
Args: []string{"orderBookL2_25:XBTUSD"}}
json, _ := json.Marshal(command)
stringJSON := string(json)
fmt.Println("JSON:", stringJSON)
connectionErr := c.WriteJSON(stringJSON)
使用两层衬垫,如下:
stringJSON := `{"op":"subscribe","args":["orderBookL2_25:XBTUSD"]}`
connectionErr := c.WriteMessage(websocket.TextMessage, []byte(stringJSON))
我正在按照此处的说明进行操作:
https://testnet.bitmex.com/app/wsAPI
并且我已经确认以下 Python 实施有效(即我这边没有网络问题等),因为:
python wsdump.py \
wss://testnet.bitmex.com/realtime
> {"op":"subscribe","args":["orderBookL2_25:XBTUSD"]}
结果
{"success":true,"subscribe":"orderBookL2_25:XBTUSD","request":{"op":"subscribe","args":["orderBookL2_25:XBTUSD"]}}
我已经尝试修改大猩猩示例代码来组合一个基本客户端:
package main
import (
"encoding/json"
"flag"
"fmt"
"log"
"net/url"
"os"
"os/signal"
"time"
"github.com/gorilla/websocket"
)
var addr = flag.String("addr", "testnet.bitmex.com", "http service address")
func main() {
flag.Parse()
log.SetFlags(0)
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
u := url.URL{Scheme: "wss", Host: *addr, Path: "/realtime"}
log.Printf("connecting to %s", u.String())
c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
if err != nil {
log.Fatal("dial:", err)
}
defer c.Close()
done := make(chan struct{})
go func() {
defer close(done)
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("read:", err)
return
}
log.Printf("recv: %s", message)
}
}()
type commandStruct struct {
Op string `json:"op"`
Args []string `json:"args"`
}
command := &commandStruct{
Op: "subscribe",
Args: []string{"orderBookL2_25:XBTUSD"}}
json, _ := json.Marshal(command)
stringJSON := string(json)
fmt.Println("JSON:", stringJSON)
connectionErr := c.WriteJSON(stringJSON)
if connectionErr != nil {
log.Println("write:", connectionErr)
}
for {
select {
case <-done:
return
case <-interrupt:
log.Println("interrupt")
// Cleanly close the connection by sending a close message and then
// waiting (with timeout) for the server to close the connection.
err := c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
if err != nil {
log.Println("write close:", err)
return
}
select {
case <-done:
case <-time.After(time.Second):
}
return
}
}
}
我的程序将以下内容打印到控制台:
{"op":"subscribe","args":["orderBookL2_25:XBTUSD"]}
与上面 Python 示例中的 JSON 相同。但随后我收到一条错误消息:
recv: {"status":400,"error":"Unrecognized request. See the docs or send 'help' for more details.","meta":{},"request":"{\"op\":\"subscribe\",\"args\":[\"orderBookL2_25:XBTUSD\"]}"}
为什么我得到不同的结果?
问题是应用程序将值双重编码为 JSON:
对 json.Marshal(command)
的调用将 command
结构编码为 JSON:
{"op":"subscribe","args":["orderBookL2_25:XBTUSD"]}
调用 c.WriteJSON(stringJSON)
将该文本编码为 JSON 并将其写入网络。双重编码的 JSON 是:
"{\"op\":\"subscribe\",\"args\":[\"orderBookL2_25:XBTUSD\"]}"
请改用以下代码:
connectionErr := c.WriteJSON(command)
我知道这是一个有点老的话题,我的回答并没有直接解决操作员提出的问题,但由于我有一个非常相似的问题,我想提出一个稍微不同的解决方案:
下面可以使用WriteMessage更直接的编码,而不是WriteJSON
type commandStruct struct {
Op string `json:"op"`
Args []string `json:"args"`
}
command := &commandStruct{
Op: "subscribe",
Args: []string{"orderBookL2_25:XBTUSD"}}
json, _ := json.Marshal(command)
stringJSON := string(json)
fmt.Println("JSON:", stringJSON)
connectionErr := c.WriteJSON(stringJSON)
使用两层衬垫,如下:
stringJSON := `{"op":"subscribe","args":["orderBookL2_25:XBTUSD"]}`
connectionErr := c.WriteMessage(websocket.TextMessage, []byte(stringJSON))