doushenyu2537
2017-02-03 21:35
浏览 70
已采纳

在AWS中使用Golang创建WebSocket

I am trying to create websockets using golang with gorilla on aws (without docker) with load balancer, I have a certificate connected to the load balancer.

I managed to make the code work with http, but when I try to use the code over https it does not work.

What am I doing wrong? When moving from http to https I changed the client request to wss instead of ws, and added the certificate to the load balancer. Here is my code. This is my main.go

    http.HandleFunc("/wss", serveWs)

fmt.Printf("Listening on port %s

", port)


if err := http.ListenAndServe(":"+port, nil); err != nil {
    fmt.Printf(err.Error())
}

This is the serveWs:

func serveWs(w http.ResponseWriter, r *http.Request) {
upgrader.CheckOrigin = func(r *http.Request) bool {
    // allow all connections by default
    return true
}

ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
    fmt.Println(err)
    if _, ok := err.(websocket.HandshakeError); !ok {
        log.Println(err)
    }
    return
}

var lastMod time.Time

if n, err := strconv.ParseInt(r.FormValue("lastMod"), 16, 64); err != nil {
    lastMod = time.Unix(0, n)
}

go writer(ws, lastMod, w, r)
reader(ws)

}

This is the request:

 var conn = new WebSocket("wss://https://www.weldpad.com/wss?" 

When I send a request from the client i get the folloing error:

failed: Error during WebSocket handshake: Unexpected response code: 400

Looking at the server log, I see.

"could not find upgrade header with token 'websocket"

This is my load balancer configuration:

Load Balancing Configuration

图片转代码服务由CSDN问答提供 功能建议

我正在尝试使用带有负载平衡器的golang和大猩猩在AWS上(无docker)使用golang创建websocket,我有证书

我设法使代码与http一起使用,但是当我尝试通过https使用代码时,它不起作用。

我在做什么错? 从http转到https时,我将客户端请求更改为wss而不是ws,并将证书添加到负载均衡器。 这是我的代码。 这是我的main.go < / p>

  http.HandleFunc(“ / wss”,serveWs)
 
fmt.Printf(“正在监听端口%s 
 
”,端口)
 
 \  nif err:= http.ListenAndServe(“:” + port,nil);  err!= nil {
 fmt.Printf(err.Error())
} 
   
 
 

这是服务:

  func serveWs(w http.ResponseWriter,r * http.Request){
upgrader.CheckOrigin = func(r * http.Request)bool {
 //默认情况下允许所有连接
返回true \  n} 
 
ws,错误:= upgrader.Upgrade(w,r,nil)
if err!= nil {
 fmt.Println(err)
如果_,确定:=错误。(websocket.HandshakeError)  ;  !ok {
 log.Println(err)
} 
 return 
} 
 
var lastMod time.Time 
 
if n,err:= strconv.ParseInt(r.FormValue(“ lastMod”),  16、64);  err!= nil {
 lastMod = time.Unix(0,n)
} 
 
go writer(ws,lastMod,w,r)
reader(ws)
   \  n 
 

}

这是请求:

  var conn = new WebSocket(“ wss:// https:  //www.weldpad.com/wss?“ 
   
 
 

当我从客户端发送请求时,出现以下错误:

失败:WebSocket握手期间出错:意外的响应代码:400

我正在查看服务器日志。

”找不到 带有令牌“ websocket”的升级头

这是我的负载均衡器配置:

负载平衡配置

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doutany76678 2017-02-03 21:51
    已采纳

    I believe it should be wss://www.weldpad.com/wss? not wss://https://www.weldpad.com/wss?

    点赞 评论

相关推荐 更多相似问题