dtu36380 2014-05-21 10:25
浏览 205
已采纳

http.Handle(“ /”,websocket.Handler(EchoServer)EchoServer可以获取ws以外的其他参数吗?

I have opened a websocket server to send data to web component,

func WebSocketServer() {
    http.Handle("/", websocket.Handler(Echoserver))
    err := http.ListenAndServe(":8081", nil)
    CheckError(err)
}

I would like to pass an additionnal argument (msg, of type String) to the handlerfunction (Echoserver).

func Echoserver(ws *websocket.Conn, msg String) {
    fmt.Println("Client Connected")
         _ := websocket.JSON.Send(ws, msg);
    }
}

Is it possible to do this with the syntax above? How do you call Echoserver with the additionnal parameter ?

  • 写回答

2条回答 默认 最新

  • doulutian4843 2014-05-21 12:33
    关注

    I assume what you want here is a consistent string parameter that is returned for all connections to /. There are a couple of approaches I've used. (None of these specific code samples have been tested; I can pull some real code if they don't compile.)

    One is to let the data be the receiver. I use this a most often with a struct, but any parameter will do. This only works for a single parameter (but you could of course put multiple parameters in a struct). I like this approach when the parameter is "object like." (Generally a struct that has other methods on it.)

    type echoStuff string
    
    var hey echoStuff = "Hey!"
    
    http.Handle("/", websocket.Handler(hey.EchoServer))
    err := http.ListenAndServe(":8081", nil)
    CheckError(err)
    
    func (msg echoStuff) Echoserver(ws *websocket.Conn) {
      fmt.Println("Client Connected")
       _ := websocket.JSON.Send(ws, msg);
    }
    

    Another way is with a closure. I like this approach when the parameter is "data like." (Something like a string or other simple data. Note how this approach doesn't require creating a local type.)

    func WebSocketServer() {
      http.Handle("/", echoHandler("Hey!"))
      err := http.ListenAndServe(":8081", nil)
      CheckError(err)
    }
    
    func echoHandler(msg string) websocket.Handler {
      return func(ws *Conn) {
        Echoserver(ws, msg)
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集