dsfsw1233 2019-03-21 01:47
浏览 374
已采纳

将golang与大猩猩websocket库一起使用,为什么WriteJson返回错误?

I'm following the instructions here:

https://testnet.bitmex.com/app/wsAPI

and I've confirmed that the following Python implementation works (ie no network issues etc from my end) because:

python wsdump.py \
  wss://testnet.bitmex.com/realtime

> {"op":"subscribe","args":["orderBookL2_25:XBTUSD"]}

results in

{"success":true,"subscribe":"orderBookL2_25:XBTUSD","request":{"op":"subscribe","args":["orderBookL2_25:XBTUSD"]}}

I've tried to modify the gorilla sample code to put together a basic client:

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
        }
    }
}

My program prints the following to the console:

{"op":"subscribe","args":["orderBookL2_25:XBTUSD"]}

which is identical to the JSON in the Python example above. But then I get an error message:

recv: {"status":400,"error":"Unrecognized request. See the docs or send 'help' for more details.","meta":{},"request":"{\"op\":\"subscribe\",\"args\":[\"orderBookL2_25:XBTUSD\"]}"}

Why do I get a different result?

  • 写回答

1条回答 默认 最新

  • drh47606 2019-03-21 02:05
    关注

    The problem is that the application is double encoding the value to JSON:

    The call to json.Marshal(command) encodes the command struct to the JSON:

    {"op":"subscribe","args":["orderBookL2_25:XBTUSD"]}
    

    The call c.WriteJSON(stringJSON) encodes that text to JSON and writes it to the network. The double encoded JSON is:

    "{\"op\":\"subscribe\",\"args\":[\"orderBookL2_25:XBTUSD\"]}"
    

    Use the following code instead:

    connectionErr := c.WriteJSON(command)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵