duanhong8839 2017-10-05 10:15
浏览 1018
已采纳

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条回答 默认 最新

    报告相同问题?

    相关推荐 更多相似问题

    悬赏问题

    • ¥15 关于机器学习创新点几个问题
    • ¥15 python程序编写
    • ¥15 Type-C扩展坞的RTL8153地址硬改
    • ¥15 uniapp websocket 发送 sub 监听后,代码自动发送了 unsub ,解除了监听
    • ¥15 nativefier封装electron的应用遇到alert弹窗后input栏获取不到焦点,confirm不弹出的问题。
    • ¥20 怎样让两台不同的电脑访问外网的IP一致?
    • ¥20 有没有认识硅云的研发 求介绍
    • ¥16 Python工时计算器改写
    • ¥15 关于#Python#的问题,如何解决?
    • ¥15 CMD 生成TXT内容输出成一行