Golang Gorilla Websocket与Web代理

时间:2016-04-01 12:50:37

标签: go proxy websocket gorilla

我正在使用Gorilla / Websocket在POC上通过Web代理与Websocket Check Website" echo.websocket.org"进行沟通。

我使用免费的在线代理" hide.me/en /"用于测试。

当我只是尝试与" echo.websocket.org" (服务器端),我的客户端站点Websocket POC达成了响应。

但是当我尝试添加代理手势时,一切都会出错:(

以下是我的代码示例:

package main

import (
    "flag"
    "log"
    "net/url"
    "os"
    "os/signal"
    "time"

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

var addrWebsocket = flag.String("addrWebsocket", "echo.websocket.org", "http service address")

func main() {
    flag.Parse()
    log.SetFlags(0)

    interrupt := make(chan os.Signal, 1)
    signal.Notify(interrupt, os.Interrupt)

    //Initialize the WebSocket URL and the Path to follow
    uWS := url.URL{Scheme: "wss", Host: *addrWebsocket}

    //Initialize the Proxy URL and the Path to follow
    uProxy, _ := url.Parse("https://hide.me/en/proxy")

    //Set the Dialer (especially the proxy)
    dialer := websocket.Dialer{
        Proxy: http.ProxyURL(uProxy),
    }
    //dialer := websocket.DefaultDialer ==> with this default dialer, it works !

    c, _, err := dialer.Dial(uWS.String(), nil) // ==> With the proxy config, it fails here !
    defer c.Close()

    done := make(chan struct{})

    go func() {
        defer c.Close()
        defer close(done)
        for {
            _, message, err := c.ReadMessage()
            if err != nil {
                log.Println("read:", err)
                return
            }
            log.Printf("recv: %s", message)
        }
    }()

    ticker := time.NewTicker(time.Second)
    defer ticker.Stop()

    for {
        select {
        case t := <-ticker.C:
            err := c.WriteMessage(websocket.TextMessage, []byte(t.String()))
            if err != nil {
                log.Println("write:", err)
                return
            }
        case <-interrupt:
            log.Println("interrupt")
            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):
                }
            c.Close()
            return
        }
    }
}

我是Go的初学者,所以如果我的代码不清楚并且干净,请不要纠正我。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

代码是正确的。服务器https://hide.me不是代理服务器。