本文整理汇总了Golang中github.com/gorilla/websocket.Dialer类的典型用法代码示例。如果您正苦于以下问题:Golang Dialer类的具体用法?Golang Dialer怎么用?Golang Dialer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Dialer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: getASocket
// getASocket calls MakeApiRequest() to get a websocket for the slack RTM
// interface.
func (b *Broker) getASocket() (*websocket.Conn, *ApiResponse, error) {
var req = ApiRequest{
URL: `https://slack.com/api/rtm.start`,
Values: make(url.Values),
Broker: b,
}
authResp, err := MakeAPIReq(req)
if err != nil {
return nil, nil, err
}
if authResp.URL == "" {
return nil, nil, fmt.Errorf("Auth failure")
}
wsURL := strings.Split(authResp.URL, "/")
wsURL[2] = wsURL[2] + ":443"
authResp.URL = strings.Join(wsURL, "/")
Logger.Debug(`Team Wesocket URL: `, authResp.URL)
var Dialer websocket.Dialer
header := make(http.Header)
header.Add("Origin", "http://localhost/")
ws, _, err := Dialer.Dial(authResp.URL, header)
if err != nil {
return nil, nil, fmt.Errorf("no dice dialing that websocket: %v", err)
}
//yay we're websocketing
return ws, authResp, nil
}
示例2: ServeHTTP
func (wp websocketProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
logger.Debug("Upgrading websocket connection.")
oconn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
logger.Error(err)
return
}
defer oconn.Close()
r.URL.Host = config.Destination
r.URL.Scheme = "ws"
dialer := websocket.Dialer{
HandshakeTimeout: time.Second,
ReadBufferSize: 1024,
WriteBufferSize: 1024,
Subprotocols: websocket.Subprotocols(r),
}
logger.Debug("Dialing", r.URL.String(), "...")
iconn, _, err := dialer.Dial(r.URL.String(), nil)
if err != nil {
logger.Error(err)
return
}
defer iconn.Close()
logger.Debug("Connected!")
go wp.Copy(oconn, iconn)
wp.Copy(iconn, oconn)
}
示例3: Hijack
func (h *Hijacker) Hijack(handle string, spec atc.HijackProcessSpec, pio ProcessIO) (int, error) {
url, header, err := h.hijackRequestParts(handle)
if err != nil {
return -1, err
}
dialer := websocket.Dialer{
TLSClientConfig: h.tlsConfig,
Proxy: http.ProxyFromEnvironment,
}
conn, _, err := dialer.Dial(url, header)
if err != nil {
return -1, err
}
defer conn.Close()
err = conn.WriteJSON(spec)
if err != nil {
return -1, err
}
inputs := make(chan atc.HijackInput, 1)
finished := make(chan struct{}, 1)
go h.monitorTTYSize(inputs, finished)
go io.Copy(&stdinWriter{inputs}, pio.In)
go h.handleInput(conn, inputs, finished)
exitStatus := h.handleOutput(conn, pio)
close(finished)
return exitStatus, nil
}
示例4: dial
func dial() (*websocket.Conn, error) {
LoadAuth()
if os.Getenv("TUTUM_STREAM_HOST") != "" {
u, _ := url.Parse(os.Getenv("TUTUM_STREAM_HOST"))
_, port, _ := net.SplitHostPort(u.Host)
if port == "" {
u.Host = u.Host + ":443"
}
StreamUrl = u.Scheme + "://" + u.Host + "/v1/"
} else if os.Getenv("TUTUM_STREAM_URL") != "" {
u, _ := url.Parse(os.Getenv("TUTUM_STREAM_URL"))
_, port, _ := net.SplitHostPort(u.Host)
if port == "" {
u.Host = u.Host + ":443"
}
StreamUrl = u.Scheme + "://" + u.Host + "/v1/"
}
Url := StreamUrl + "events/"
header := http.Header{}
header.Add("Authorization", AuthHeader)
header.Add("User-Agent", customUserAgent)
var Dialer websocket.Dialer
ws, _, err := Dialer.Dial(Url, header)
if err != nil {
return nil, err
}
return ws, nil
}
示例5: Logs
func (self *Service) Logs(c chan Logs) {
endpoint := ""
if Namespace != "" {
endpoint = "api/app/" + appSubsystemVersion + "/" + Namespace + "/service/" + self.Uuid + "/logs/"
} else {
endpoint = "api/app/" + appSubsystemVersion + "/service/" + self.Uuid + "/logs/"
}
url := StreamUrl + endpoint
header := http.Header{}
header.Add("Authorization", AuthHeader)
header.Add("User-Agent", customUserAgent)
var Dialer websocket.Dialer
ws, _, err := Dialer.Dial(url, header)
if err != nil {
log.Println(err)
}
var msg Logs
for {
if err = ws.ReadJSON(&msg); err != nil {
log.Println(err)
break
}
c <- msg
}
}
示例6: wsDial
func wsDial(src v2net.Address, dest v2net.Destination) (*wsconn, error) {
commonDial := func(network, addr string) (net.Conn, error) {
return internet.DialToDest(src, dest)
}
tlsconf := &tls.Config{ServerName: dest.Address().Domain(), InsecureSkipVerify: effectiveConfig.DeveloperInsecureSkipVerify}
dialer := websocket.Dialer{NetDial: commonDial, ReadBufferSize: 65536, WriteBufferSize: 65536, TLSClientConfig: tlsconf}
effpto := calcPto(dest)
uri := func(dst v2net.Destination, pto string, path string) string {
return fmt.Sprintf("%v://%v/%v", pto, dst.NetAddr(), path)
}(dest, effpto, effectiveConfig.Path)
conn, resp, err := dialer.Dial(uri, nil)
if err != nil {
if resp != nil {
reason, reasonerr := ioutil.ReadAll(resp.Body)
log.Info(string(reason), reasonerr)
}
return nil, err
}
return func() internet.Connection {
connv2ray := &wsconn{wsc: conn, connClosing: false}
connv2ray.setup()
return connv2ray
}().(*wsconn), nil
}
示例7: ConnectToHead
func ConnectToHead(url string, secret string) {
var cstDialer = websocket.Dialer{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
conn, _, err := cstDialer.Dial(url, nil)
if err != nil {
fmt.Printf("Dial: %v", err)
}
log.Printf("ok")
// Send a welcome packet for auth
conn.WriteJSON(&common.Packet{
Cmd: "auth",
Context: secret,
})
for {
var p common.Packet
if err := conn.ReadJSON(&p); err != nil {
log.Println("Error reading head's json: ", err)
return
}
response := HandlePacket(p)
if response != nil {
conn.WriteJSON(response)
}
}
}
示例8: startClient
func startClient(url *url.URL, wg *sync.WaitGroup, chRequests chan stats.MessageRequest,
chResponse chan *Response, id int) {
dialer := websocket.Dialer{}
conn, _, err := dialer.Dial(url.String(), nil)
if err != nil {
log.Fatal("Failed to establish connection with server: ", err)
}
defer conn.Close()
start := time.Now()
connected := true
var clientWg sync.WaitGroup
go func() {
for connected {
var mresp stats.MessageResponse
if err := conn.ReadJSON(&mresp); err != nil {
if connected {
log.Error("Error reading json response: ", err)
chResponse <- &Response{
Success: false,
}
clientWg.Done()
wg.Done()
}
} else {
log.Debug("Received response Host:", mresp.Host)
duration := time.Since(start)
chResponse <- &Response{
Success: true,
Duration: duration,
Valid: validateNodes(&mresp),
}
clientWg.Done()
wg.Done()
}
}
}()
for mreq := range chRequests {
clientWg.Add(1)
if err := conn.WriteJSON(&mreq); err != nil {
log.Error("Failed to send req: ", err)
clientWg.Done()
} else {
start = time.Now()
log.Debug("Sent req: ", mreq)
}
}
clientWg.Wait()
connected = false
}
示例9: Run
func (self *Container) Run(command string, c chan Exec) {
endpoint := "container/" + self.Uuid + "/exec/?user=" + User + "&token=" + ApiKey + "&command=" + url.QueryEscape(command)
url := StreamUrl + endpoint
header := http.Header{}
header.Add("User-Agent", customUserAgent)
var Dialer websocket.Dialer
ws, _, err := Dialer.Dial(url, header)
if err != nil {
log.Println(err)
}
var msg Exec
for {
if err = ws.ReadJSON(&msg); err != nil {
if err != nil && err.Error() != "EOF" {
log.Println(err)
} else {
break
}
}
c <- msg
}
}
示例10: main
func main() {
// logger.SetConsole(true)
// logger.SetRollingDaily(".", "test.log")
// logger.SetLevel(logger.ALL)
flag.Parse()
var addr = flag.String("addr", "localhost:8080", "http service address")
var dialer = websocket.Dialer{}
u := url.URL{Scheme: "ws", Host: *addr, Path: "/gows"}
for {
errCh := make(chan error)
ws, _, err := dialer.Dial(u.String(), nil)
defer ws.Close()
if err == nil {
fmt.Println("runing")
go readMessages(ws, errCh)
go writeMessages(ws)
fmt.Println(<-errCh)
close(errCh)
}
if ws != nil {
ws.Close()
}
fmt.Println("reconning....")
time.Sleep(5 * time.Second)
}
}
示例11: newWebsocketPeer
func newWebsocketPeer(url, protocol, origin string, serializer Serializer, payloadType int) (Peer, error) {
dialer := websocket.Dialer{
Subprotocols: []string{protocol},
}
conn, _, err := dialer.Dial(url, nil)
if err != nil {
return nil, err
}
ep := &websocketPeer{
conn: conn,
messages: make(chan Message, 10),
serializer: serializer,
payloadType: payloadType,
}
go func() {
for {
// TODO: use conn.NextMessage() and stream
// TODO: do something different based on binary/text frames
if _, b, err := conn.ReadMessage(); err != nil {
conn.Close()
break
} else {
msg, err := serializer.Deserialize(b)
if err != nil {
// TODO: handle error
} else {
ep.messages <- msg
}
}
}
}()
return ep, nil
}
示例12: Logs
func (self *Container) Logs(c chan Logs) {
endpoint := "container/" + self.Uuid + "/logs/?user=" + User + "&token=" + ApiKey
url := StreamUrl + endpoint
header := http.Header{}
header.Add("User-Agent", customUserAgent)
var Dialer websocket.Dialer
ws, _, err := Dialer.Dial(url, header)
if err != nil {
log.Println(err)
}
var msg Logs
for {
if err = ws.ReadJSON(&msg); err != nil {
if err != nil && err.Error() != "EOF" {
log.Println(err)
} else {
break
}
}
c <- msg
}
}
示例13: TestMainCLI
func TestMainCLI(t *testing.T) {
Convey("when I run the app", t, func() {
port := 9003
ctx, cancelFunc := context.WithCancel(context.Background())
app := MakeCliApp(ctx)
go app.Run([]string{"<executable path>", "--port", strconv.Itoa(port)})
time.Sleep(time.Millisecond)
url := fmt.Sprintf("ws://localhost:%v/", port)
d := websocket.Dialer{}
Convey("and connect", func() {
conn, _, err := d.Dial(url, http.Header{})
So(err, ShouldBeNil)
conn.Close()
})
Reset(func() {
cancelFunc()
time.Sleep(5 * time.Millisecond)
So("subicul", testutils.ShouldNotBeRunningGoroutines)
})
})
}
示例14: ConnectWebsocketSession
// ConnectWebsocketSession dials the remote specified in the opts and
// creates new websocket session.
func ConnectWebsocketSession(opts *DialOptions) (*WebsocketSession, error) {
dialURL, err := url.Parse(opts.BaseURL)
if err != nil {
return nil, err
}
// will be used to set the origin header
originalScheme := dialURL.Scheme
if err := replaceSchemeWithWS(dialURL); err != nil {
return nil, err
}
if err := addMissingPortAndSlash(dialURL); err != nil {
return nil, err
}
serverID := threeDigits()
sessionID := utils.RandomString(20)
// Add server_id and session_id to the path.
dialURL.Path += serverID + "/" + sessionID + "/websocket"
requestHeader := http.Header{}
requestHeader.Add("Origin", originalScheme+"://"+dialURL.Host)
ws := websocket.Dialer{
ReadBufferSize: opts.ReadBufferSize,
WriteBufferSize: opts.WriteBufferSize,
}
// if the user passed a custom HTTP client and its transport
// is of *http.Transport type - we're using its Dial field
// for connecting to remote host
if t, ok := opts.Client().Transport.(*http.Transport); ok {
ws.NetDial = t.Dial
}
// if the user passed a timeout, use a dial with a timeout
if opts.Timeout != 0 && ws.NetDial == nil {
// If ws.NetDial is non-nil then gorilla does not
// use ws.HandshakeTimeout for the deadlines.
//
// Instead we're going to set it ourselves.
ws.NetDial = (&net.Dialer{
Timeout: opts.Timeout,
Deadline: time.Now().Add(opts.Timeout),
}).Dial
}
conn, _, err := ws.Dial(dialURL.String(), requestHeader)
if err != nil {
return nil, err
}
session := NewWebsocketSession(conn)
session.id = sessionID
return session, nil
}
示例15: Connect
func Connect(address, user, pass string) (*websocket.Conn, *http.Response, error) {
authkey := base64.StdEncoding.EncodeToString([]byte(user + ":" + pass))
hdr := make(http.Header)
hdr.Add("Authorization", "Basic "+authkey)
var dialer websocket.Dialer
conn, resp, err := dialer.Dial("ws://"+address, hdr)
return conn, resp, err
}