本文整理匯總了Golang中code/google/com/p/go/net/websocket.DialConfig函數的典型用法代碼示例。如果您正苦於以下問題:Golang DialConfig函數的具體用法?Golang DialConfig怎麽用?Golang DialConfig使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了DialConfig函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: ConnectOnce
func (c *WebsocketClient) ConnectOnce() error {
c.logger.Debug("ConnectOnce:call")
defer c.logger.Debug("ConnectOnce:return")
// Make websocket connection. If this fails, either API is down or the ws
// address is wrong.
link := c.api.AgentLink(c.link)
c.logger.Debug("ConnectOnce:link:" + link)
config, err := websocket.NewConfig(link, c.api.Origin())
if err != nil {
return err
}
config.Header.Add("X-Percona-API-Key", c.api.ApiKey())
c.logger.Debug("ConnectOnce:websocket.DialConfig")
c.status.Update(c.name, "Connecting "+link)
conn, err := websocket.DialConfig(config)
if err != nil {
return err
}
c.mux.Lock()
defer c.mux.Unlock()
c.connected = true
c.conn = conn
c.status.Update(c.name, "Connected "+link)
return nil
}
示例2: newWebsocketDialer
// newWebsocketDialer returns a function that
// can be passed to utils/parallel.Try.Start.
func newWebsocketDialer(cfg *websocket.Config, opts DialOpts) func(<-chan struct{}) (io.Closer, error) {
openAttempt := utils.AttemptStrategy{
Total: opts.Timeout,
Delay: opts.RetryDelay,
}
return func(stop <-chan struct{}) (io.Closer, error) {
for a := openAttempt.Start(); a.Next(); {
select {
case <-stop:
return nil, parallel.ErrStopped
default:
}
logger.Infof("dialing %q", cfg.Location)
conn, err := websocket.DialConfig(cfg)
if err == nil {
return conn, nil
}
if a.HasNext() {
logger.Debugf("error dialing %q, will retry: %v", cfg.Location, err)
} else {
logger.Infof("error dialing %q: %v", cfg.Location, err)
return nil, fmt.Errorf("unable to connect to %q", cfg.Location)
}
}
panic("unreachable")
}
}
示例3: HandleWebSocket
func (proxy *Proxy) HandleWebSocket(clientWS *websocket.Conn) {
req := clientWS.Request()
req.ParseForm()
req.Form.Get("app")
clientAddress := clientWS.RemoteAddr()
appId := req.Form.Get("app")
extractAuthTokenFromUrl := func(u *url.URL) string {
authorization := ""
queryValues := u.Query()
if len(queryValues["authorization"]) == 1 {
authorization = queryValues["authorization"][0]
}
return authorization
}
authToken := clientWS.Request().Header.Get("Authorization")
if authToken == "" {
authToken = extractAuthTokenFromUrl(req.URL)
}
if authorized, errorMessage := proxy.isAuthorized(appId, authToken, clientAddress); !authorized {
data, err := proto.Marshal(errorMessage)
if err != nil {
proxy.logger.Errorf("Error marshalling log message: %s", err)
}
websocket.Message.Send(clientWS, data)
clientWS.Close()
return
}
defer clientWS.Close()
proxy.logger.Debugf("Output Proxy: Request for app: %v", req.Form.Get("app"))
serverWSs := make([]*websocket.Conn, len(proxy.hashers))
for index, hasher := range proxy.hashers {
proxy.logger.Debugf("Output Proxy: Servers in group [%v]: %v", index, hasher.LoggregatorServers())
server := hasher.GetLoggregatorServerForAppId(appId)
proxy.logger.Debugf("Output Proxy: AppId is %v. Using server: %v", appId, server)
config, err := websocket.NewConfig("ws://"+server+req.URL.RequestURI(), "http://localhost")
if err != nil {
proxy.logger.Errorf("Output Proxy: Error creating config for websocket - %v", err)
}
serverWS, err := websocket.DialConfig(config)
if err != nil {
proxy.logger.Errorf("Output Proxy: Error connecting to loggregator server - %v", err)
}
if serverWS != nil {
serverWSs[index] = serverWS
}
}
proxy.forwardIO(serverWSs, clientWS)
}
示例4: connectToWebsocket
func (repo LoggregatorLogsRepository) connectToWebsocket(location string, app cf.Application, onConnect func(), outputChan chan *logmessage.Message, stopLoggingChan chan bool, printTimeBuffer time.Duration) (err error) {
trace.Logger.Printf("\n%s %s\n", terminal.HeaderColor("CONNECTING TO WEBSOCKET:"), location)
config, err := websocket.NewConfig(location, "http://localhost")
if err != nil {
return
}
config.Header.Add("Authorization", repo.config.AccessToken)
config.TlsConfig = &tls.Config{InsecureSkipVerify: true}
ws, err := websocket.DialConfig(config)
if err != nil {
return
}
onConnect()
inputChan := make(chan *logmessage.Message, 1000)
go repo.sendKeepAlive(ws)
go repo.listenForMessages(ws, inputChan, stopLoggingChan)
go makeAndStartMessageSorter(inputChan, outputChan, stopLoggingChan, printTimeBuffer)
return
}
示例5: connectToWebsocket
func (repo LoggregatorLogsRepository) connectToWebsocket(location string, onConnect func(), outputChan chan *logmessage.Message, stopLoggingChan chan bool, printTimeBuffer time.Duration) (err error) {
trace.Logger.Printf("\n%s %s\n", terminal.HeaderColor("CONNECTING TO WEBSOCKET:"), location)
config, err := websocket.NewConfig(location, "http://localhost")
if err != nil {
return
}
config.Header.Add("Authorization", repo.config.AccessToken)
config.TlsConfig = &tls.Config{InsecureSkipVerify: true}
ws, err := websocket.DialConfig(config)
if err != nil {
return
}
defer ws.Close()
onConnect()
go repo.sendKeepAlive(ws)
inputChan := make(chan *logmessage.Message, LogBufferSize)
stopInputChan := make(chan bool, 1)
go func() {
defer close(stopInputChan)
defer close(inputChan)
repo.listenForMessages(ws, inputChan, stopInputChan)
}()
messageQueue := &SortedMessageQueue{printTimeBuffer: printTimeBuffer}
repo.processMessages(messageQueue, inputChan, outputChan, stopLoggingChan, stopInputChan)
return
}
示例6: New
func New(key, secret string, currencies ...string) (*StreamingApi, error) {
url := fmt.Sprintf("%s%s?Currency=%s", api_host, api_path, strings.Join(currencies, ","))
config, _ := websocket.NewConfig(url, origin_url)
ws, err := websocket.DialConfig(config)
if err != nil {
return nil, err
}
api := &StreamingApi{
ws: ws,
Ticker: make(chan Ticker),
Info: make(chan Info),
Depth: make(chan Depth),
Trade: make(chan Trade),
Orders: make(chan []Order),
}
api.key, err = hex.DecodeString(strings.Replace(key, "-", "", -1))
if err != nil {
return nil, err
}
api.secret, err = base64.StdEncoding.DecodeString(secret)
if err != nil {
return nil, err
}
return api, err
}
示例7: New
func New(cfg *websocket.Config) (*JsonWebsocket, error) {
ws, err := websocket.DialConfig(cfg)
if err != nil {
return nil, err
}
return &JsonWebsocket{ws: ws}, nil
}
示例8: KeepAliveClient
func KeepAliveClient(t *testing.T, port string, path string) {
config, err := websocket.NewConfig("ws://localhost:"+port+path, "http://localhost")
config.Header.Add("Authorization", testhelpers.VALID_AUTHENTICATION_TOKEN)
assert.NoError(t, err)
ws, err := websocket.DialConfig(config)
assert.NoError(t, err)
websocket.Message.Send(ws, []byte("keep alive"))
}
示例9: dialWebsocketFromURL
func (s *debugLogSuite) dialWebsocketFromURL(c *gc.C, server string, header http.Header) (*websocket.Conn, error) {
c.Logf("dialing %v", server)
config, err := websocket.NewConfig(server, "http://localhost/")
c.Assert(err, gc.IsNil)
config.Header = header
caCerts := x509.NewCertPool()
c.Assert(caCerts.AppendCertsFromPEM([]byte(testing.CACert)), jc.IsTrue)
config.TlsConfig = &tls.Config{RootCAs: caCerts, ServerName: "anything"}
return websocket.DialConfig(config)
}
示例10: NewClient
// Create a New SocketCluster Client
func NewClient(auth AuthDetails, dbpath string) (*Client, error) {
Info = log.New(os.Stdout, "SOCKETCLUSTER: ", log.Ltime|log.Lshortfile)
origin := "http://localhost"
prefix := "ws"
if auth.SecureWS {
prefix = "wss"
}
url := fmt.Sprintf("%s://%s/socketcluster/", prefix, auth.Host)
config, _ := websocket.NewConfig(url, origin)
config.Header.Add("User-Agent", auth.UserAgent)
Info.Println("Connecting: " + url)
ws, err := websocket.DialConfig(config)
if err != nil {
Info.Println(err)
return nil, err
}
c := &Client{
ws: ws,
id: 0,
mutex: &sync.Mutex{},
quitChan: make(chan int),
}
c.setupDB(dbpath)
// Connection succeded. Send a handshake event.
c.emit(c.NewEvent("#handshake", makeHandshakeData()))
rEvent, err := c.recieve()
if err != nil {
Info.Println(err)
return nil, errors.New("#handshake recieve error")
}
// Start listening to events
go c.listen()
if rEvent.Rid == 1 {
if !isAuthenticated(rEvent) {
c.emit(c.NewEvent("clearoldsessions", makeClearOldSessionsData(auth)))
c.loginEvent = c.NewEvent("login", makeLoginData(auth))
c.emit(c.loginEvent)
}
}
return c, nil
}
示例11: RunClient
func RunClient(url string, id string, userKey string) {
rootPath, _ = filepath.Abs(rootPath)
ListenForSignals()
socketUrl := fmt.Sprintf("%s/clientsocket", url)
var ws *websocket.Conn
var timeout time.Duration = 1e8
config, err := websocket.NewConfig(socketUrl, socketUrl)
if err != nil {
fmt.Println(err)
return
}
config.TlsConfig = new(tls.Config)
// Disable this when getting a proper certificate
config.TlsConfig.InsecureSkipVerify = true
for {
time.Sleep(timeout)
var err error
ws, err = websocket.DialConfig(config)
timeout *= 2
if err != nil {
fmt.Println("Could not yet connect:", err.Error(), ", trying again in", timeout)
} else {
break
}
}
buffer, _ := json.Marshal(HelloMessage{"0.1", id, userKey})
if _, err := ws.Write(buffer); err != nil {
log.Fatal(err)
return
}
connectUrl := strings.Replace(url, "ws://", "http://", 1)
connectUrl = strings.Replace(connectUrl, "wss://", "https://", 1)
multiplexer := NewRPCMultiplexer(ws, handleRequest)
if userKey == "" {
fmt.Print("In the Zed application copy and paste following URL to edit:\n\n")
fmt.Printf(" %s/fs/%s\n\n", connectUrl, id)
} else {
fmt.Println("A Zed window should now open. If not, make sure Zed is running and configured with the correct userKey.")
}
fmt.Println("Press Ctrl-c to quit.")
err = multiplexer.Multiplex()
if err != nil {
// TODO do this in a cleaner way (reconnect, that is)
if err.Error() == "no-client" {
fmt.Printf("ERROR: Your Zed editor is not currently connected to zedrem server %s.\nBe sure Zed is running and the project picker is open.\n", url)
} else {
RunClient(url, id, userKey)
}
}
}
示例12: dialWebsocket
func dialWebsocket(c *gc.C, addr, path string) (*websocket.Conn, error) {
origin := "http://localhost/"
url := fmt.Sprintf("wss://%s%s", addr, path)
config, err := websocket.NewConfig(url, origin)
c.Assert(err, gc.IsNil)
pool := x509.NewCertPool()
xcert, err := cert.ParseCert(coretesting.CACert)
c.Assert(err, gc.IsNil)
pool.AddCert(xcert)
config.TlsConfig = &tls.Config{RootCAs: pool}
return websocket.DialConfig(config)
}
示例13: AssertConnectionFails
func AssertConnectionFails(t *testing.T, port string, path string, expectedErrorCode uint16) {
config, err := websocket.NewConfig("ws://localhost:"+port+path, "http://localhost")
assert.NoError(t, err)
ws, err := websocket.DialConfig(config)
assert.NoError(t, err)
data := make([]byte, 2)
_, err = ws.Read(data)
errorCode := binary.BigEndian.Uint16(data)
assert.Equal(t, expectedErrorCode, errorCode)
assert.Equal(t, "EOF", err.Error())
}
示例14: Open
func Open(info *Info, opts DialOpts) (*State, error) {
// TODO Select a random address from info.Addrs
// and only fail when we've tried all the addresses.
// TODO what does "origin" really mean, and is localhost always ok?
cfg, err := websocket.NewConfig("wss://"+info.Addrs[0]+"/", "http://localhost/")
if err != nil {
return nil, err
}
pool := x509.NewCertPool()
xcert, err := cert.ParseCert(info.CACert)
if err != nil {
return nil, err
}
pool.AddCert(xcert)
cfg.TlsConfig = &tls.Config{
RootCAs: pool,
ServerName: "anything",
}
var conn *websocket.Conn
openAttempt := utils.AttemptStrategy{
Total: opts.Timeout,
Delay: opts.RetryDelay,
}
for a := openAttempt.Start(); a.Next(); {
log.Infof("state/api: dialing %q", cfg.Location)
conn, err = websocket.DialConfig(cfg)
if err == nil {
break
}
log.Errorf("state/api: %v", err)
}
if err != nil {
return nil, err
}
log.Infof("state/api: connection established")
client := rpc.NewConn(jsoncodec.NewWebsocket(conn))
client.Start()
st := &State{
client: client,
conn: conn,
}
if info.Tag != "" || info.Password != "" {
if err := st.Login(info.Tag, info.Password, info.Nonce); err != nil {
conn.Close()
return nil, err
}
}
st.broken = make(chan struct{})
go st.heartbeatMonitor()
return st, nil
}
示例15: WaitForServerStart
func WaitForServerStart(port string, path string) {
serverStarted := func() bool {
config, err := websocket.NewConfig("ws://localhost:"+port+path, "http://localhost")
_, err = websocket.DialConfig(config)
if err != nil {
return false
}
return true
}
for !serverStarted() {
time.Sleep(1 * time.Microsecond)
}
}