duanhong8839
2017-10-05 10:15 阅读 678
已采纳

Golang WebSocket客户端,获取结果后关闭连接

How I can implement this kind of scenario:

1.I have LoginHandler which receives some user data - email and signedXml:

func LoginHandler(c *gin.Context) {
    var (
        err  error
        data LoginPost
    )
    if err = c.BindJSON(&data); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"status": "error"})
        return
    }

    ...

    c.JSON(http.StatusOK, gin.H{"status": "ok"})
}

2.I need to send signedXml to another server via websocket

3.Save result (success or error)

4.Close connection

Every HTTP request will open connection, send 1 message, get 1 result and finally close socket. I was trying with channel, but no success. Is this possible to implement my case?

UPDATE

package main

import (
    "log"
    "net/url"

    "github.com/gorilla/mux"
    "github.com/gorilla/websocket"
    "net/http"
)

func indexHandler(w http.ResponseWriter, r *http.Request) {
    message := r.FormValue("message")
    w.Write([]byte(message))
}

func postHandler(w http.ResponseWriter, r *http.Request) {
    var (
        message = r.FormValue("message")
        u = url.URL{Scheme: "ws", Host: "echo.websocket.org", Path: "/"}
        err error
        out []byte
        conn *websocket.Conn
    )
    log.Printf("message: %s
", message)
    log.Printf("connecting to %s
", u.String())
    conn, _, err = websocket.DefaultDialer.Dial(u.String(), nil)
    if err != nil {
        log.Fatal("dial:", err)
    }
    log.Println("write")
    if err = conn.WriteMessage(websocket.TextMessage, []byte(message)); err != nil {
        log.Fatal("write:", err)
    }
    log.Println("read")
    if _, out, err = conn.ReadMessage(); err != nil {
        log.Fatal("read:", err)
    }
    w.Write(out)
    log.Println("close")
    conn.Close()
}

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/", indexHandler).Methods("GET")
    r.HandleFunc("/post", postHandler).Methods("POST")
    http.Handle("/", r)
    http.ListenAndServe(":8080", nil)
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    dpp78272 dpp78272 2017-10-05 15:42

    Call Dial, WriteMessage, ReadMessage and Close in sequence.

    c, _, err := websocket.DefaultDialer.Dial(url, nil)
    if err != nil {
        // handle error
    }
    err := c.WriteMessage(websocket.TextMessage, signedXML)
    if err != nil {
         // handle error
    }
    _, p, err := c.ReadMessage()
    if err != nil {
         // handle error
    }
    c.Close()
    
    // p is a []byte with the first received message.
    
    点赞 评论 复制链接分享

相关推荐