• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang tls.Dial函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中crypto/tls.Dial函数的典型用法代码示例。如果您正苦于以下问题:Golang Dial函数的具体用法?Golang Dial怎么用?Golang Dial使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了Dial函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: Open

// Connects the socket, creating a new socket object if necessary.
func (p *TSSLSocket) Open() error {
	var err error
	// If we have a hostname, we need to pass the hostname to tls.Dial for
	// certificate hostname checks.
	if p.hostPort != "" {
		if p.conn, err = tls.Dial("tcp", p.hostPort, p.cfg); err != nil {
			return NewTTransportException(NOT_OPEN, err.Error())
		}
	} else {
		if p.IsOpen() {
			return NewTTransportException(ALREADY_OPEN, "Socket already connected.")
		}
		if p.addr == nil {
			return NewTTransportException(NOT_OPEN, "Cannot open nil address.")
		}
		if len(p.addr.Network()) == 0 {
			return NewTTransportException(NOT_OPEN, "Cannot open bad network name.")
		}
		if len(p.addr.String()) == 0 {
			return NewTTransportException(NOT_OPEN, "Cannot open bad address.")
		}
		if p.conn, err = tls.Dial(p.addr.Network(), p.addr.String(), p.cfg); err != nil {
			return NewTTransportException(NOT_OPEN, err.Error())
		}
	}
	return nil
}
开发者ID:ConfusedReality,项目名称:pkg_serialization_fbthrift,代码行数:28,代码来源:ssl_socket.go


示例2: dial

func (t *TLSRedialTransport) dial(network, addr string) (conn net.Conn, err error) {
	t.once.Do(func() {
		conn = t.ServerConn
	})
	if conn != nil {
		return conn, nil
	}

	newConn, err := tls.Dial("tcp", t.serverAddr, &tls.Config{
		ServerName:         t.ServerName,
		InsecureSkipVerify: true,
	})
	if err != nil {
		return nil, err
	}

	if !bytes.Equal(t.publicKey, newConn.ConnectionState().PeerCertificates[0].RawSubjectPublicKeyInfo) {
		newConn.Close()
		log.Printf("TLS private key at %s changed", t.ServerName)

		// Our little certificate-pinning trick failed because the server changed
		// certificates (or we've been MITM'd). See if the server has a valid
		// certificate, even if it's not the same one.
		return tls.Dial("tcp", t.serverAddr, &tls.Config{ServerName: t.ServerName})
	}

	return newConn, nil
}
开发者ID:ranivishnu,项目名称:redwood,代码行数:28,代码来源:transport.go


示例3: FromURL

// FromURL connects to the given URL.Host via tls.Dial with the given tls.Config and populates the HostCertificateInfo
// via tls.ConnectionState.  If the certificate was verified with the given tls.Config, the Err field will be nil.
// Otherwise, Err will be set to the x509.UnknownAuthorityError or x509.HostnameError.
// If tls.Dial returns an error of any other type, that error is returned.
func (info *HostCertificateInfo) FromURL(u *url.URL, config *tls.Config) error {
	addr := u.Host
	if !(strings.LastIndex(addr, ":") > strings.LastIndex(addr, "]")) {
		addr += ":443"
	}

	conn, err := tls.Dial("tcp", addr, config)
	if err != nil {
		switch err.(type) {
		case x509.UnknownAuthorityError:
		case x509.HostnameError:
		default:
			return err
		}

		info.Err = err

		conn, err = tls.Dial("tcp", addr, &tls.Config{InsecureSkipVerify: true})
		if err != nil {
			return err
		}
	} else {
		info.Status = string(types.HostCertificateManagerCertificateInfoCertificateStatusGood)
	}

	state := conn.ConnectionState()
	_ = conn.Close()
	info.FromCertificate(state.PeerCertificates[0])

	return nil
}
开发者ID:vmware,项目名称:vic,代码行数:35,代码来源:host_certificate_info.go


示例4: connect

// connect to the server. Here we keep trying every 10 seconds until we manage
// to Dial to the server.
func (bot *ircBot) connect() (conn io.ReadWriteCloser) {

	var (
		err     error
		counter int
	)

	connectTimeout := time.After(0)

	bot.Lock()
	bot.isConnecting = true
	bot.isAuthenticating = false
	bot.Unlock()

	for {
		select {
		case <-connectTimeout:
			counter++
			connectTimeout = nil
			glog.Infoln("[Info] Connecting to IRC server: ", bot.address)
			conn, err = tls.Dial("tcp", bot.address, nil) // Always try TLS first
			if err == nil {
				glog.Infoln("Connected: TLS secure")
				return conn
			} else if _, ok := err.(x509.HostnameError); ok {
				glog.Errorln("Could not connect using TLS because: ", err)
				// Certificate might not match. This happens on irc.cloudfront.net
				insecure := &tls.Config{InsecureSkipVerify: true}
				conn, err = tls.Dial("tcp", bot.address, insecure)

				if err == nil && isCertValid(conn.(*tls.Conn)) {
					glog.Errorln("Connected: TLS with awkward certificate")
					return conn
				}
			} else if _, ok := err.(x509.UnknownAuthorityError); ok {
				glog.Errorln("x509.UnknownAuthorityError : ", err)
				insecure := &tls.Config{InsecureSkipVerify: true}
				conn, err = tls.Dial("tcp", bot.address, insecure)
				if err == nil {
					glog.Infoln("Connected: TLS with an x509.UnknownAuthorityError", err)
					return conn
				}
			} else {
				glog.Errorln("Could not establish a tls connection", err)

			}

			conn, err = net.Dial("tcp", bot.address)
			if err == nil {
				glog.Infoln("Connected: Plain text insecure")
				return conn
			}
			// TODO (yml) At some point we might want to panic
			delay := 5 * counter
			glog.Infoln("IRC Connect error. Will attempt to re-connect. ", err, "in", delay, "seconds")
			connectTimeout = time.After(time.Duration(delay) * time.Second)
		}
	}
}
开发者ID:fazzzmZozo,项目名称:botbot-bot,代码行数:61,代码来源:irc.go


示例5: BundleFromRemote

// BundleFromRemote fetches the certificate chain served by the server at
// serverName (or ip, if the ip argument is not the empty string). It
// is expected that the method will be able to make a connection at
// port 443. The chain used by the server in this connection is
// used to rebuild the bundle.
func (b *Bundler) BundleFromRemote(serverName, ip string) (*Bundle, error) {
	config := &tls.Config{
		RootCAs:    b.RootPool,
		ServerName: serverName,
	}

	// Dial by IP if present
	var dialName string
	if ip != "" {
		dialName = ip + ":443"
	} else {
		dialName = serverName + ":443"
	}

	log.Debugf("bundling from remote %s", dialName)
	conn, err := tls.Dial("tcp", dialName, config)
	var dialError string
	// If there's an error in tls.Dial, try again with
	// InsecureSkipVerify to fetch the remote bundle to (re-)bundle with.
	// If the bundle is indeed not usable (expired, mismatched hostnames, etc.),
	// report the error.
	// Otherwise, create a working bundle and insert the tls error in the bundle.Status.
	if err != nil {
		log.Debugf("dial failed: %v", err)
		// record the error msg
		dialError = fmt.Sprintf("Failed rigid TLS handshake with %s: %v", dialName, err)
		// dial again with InsecureSkipVerify
		log.Debugf("try again with InsecureSkipVerify.")
		config.InsecureSkipVerify = true
		conn, err = tls.Dial("tcp", dialName, config)
		if err != nil {
			log.Debugf("dial with InsecureSkipVerify failed: %v", err)
			return nil, errors.New(errors.DialError, errors.Unknown, err)
		}
	}

	connState := conn.ConnectionState()

	certs := connState.PeerCertificates

	err = conn.VerifyHostname(serverName)
	if err != nil {
		log.Debugf("failed to verify hostname: %v", err)
		return nil, errors.New(errors.CertificateError, errors.VerifyFailed, err)
	}
	// verify peer intermediates and store them if there is any missing from the bundle.
	// Don't care if there is error, will throw it any way in Bundle() call.
	b.fetchIntermediates(certs)

	// Bundle with remote certs. Inject the initial dial error, if any, to the status reporting.
	bundle, err := b.Bundle(certs, nil, Ubiquitous)
	if err != nil {
		return nil, err
	} else if dialError != "" {
		bundle.Status.Messages = append(bundle.Status.Messages, dialError)
	}
	return bundle, err
}
开发者ID:kalw,项目名称:cfssl,代码行数:63,代码来源:bundler.go


示例6: TestWithClientCertificateAuthenticationMultipeCAsMultipleFiles

// TestWithClientCertificateAuthentication
// Use two CA:s in two different files and test that clients with client signed by either of them can connect
func (s *HTTPSSuite) TestWithClientCertificateAuthenticationMultipeCAsMultipleFiles(c *check.C) {
	cmd := exec.Command(traefikBinary, "--configFile=fixtures/https/clientca/https_2ca2config.toml")
	err := cmd.Start()
	c.Assert(err, checker.IsNil)
	defer cmd.Process.Kill()

	time.Sleep(500 * time.Millisecond)

	tlsConfig := &tls.Config{
		InsecureSkipVerify: true,
		ServerName:         "snitest.com",
		Certificates:       []tls.Certificate{},
	}
	// Connection without client certificate should fail
	conn, err := tls.Dial("tcp", "127.0.0.1:4443", tlsConfig)
	c.Assert(err, checker.NotNil, check.Commentf("should not be allowed to connect to server"))

	// Connect with client signed by ca1
	cert, err := tls.LoadX509KeyPair("fixtures/https/clientca/client1.crt", "fixtures/https/clientca/client1.key")
	c.Assert(err, checker.IsNil, check.Commentf("unable to load client certificate and key"))
	tlsConfig.Certificates = append(tlsConfig.Certificates, cert)

	conn, err = tls.Dial("tcp", "127.0.0.1:4443", tlsConfig)
	c.Assert(err, checker.IsNil, check.Commentf("failed to connect to server"))

	conn.Close()

	// Connect with client signed by ca2
	tlsConfig = &tls.Config{
		InsecureSkipVerify: true,
		ServerName:         "snitest.com",
		Certificates:       []tls.Certificate{},
	}
	cert, err = tls.LoadX509KeyPair("fixtures/https/clientca/client2.crt", "fixtures/https/clientca/client2.key")
	c.Assert(err, checker.IsNil, check.Commentf("unable to load client certificate and key"))
	tlsConfig.Certificates = append(tlsConfig.Certificates, cert)

	conn, err = tls.Dial("tcp", "127.0.0.1:4443", tlsConfig)
	c.Assert(err, checker.IsNil, check.Commentf("failed to connect to server"))
	conn.Close()

	// Connect with client signed by ca3 should fail
	tlsConfig = &tls.Config{
		InsecureSkipVerify: true,
		ServerName:         "snitest.com",
		Certificates:       []tls.Certificate{},
	}
	cert, err = tls.LoadX509KeyPair("fixtures/https/clientca/client3.crt", "fixtures/https/clientca/client3.key")
	c.Assert(err, checker.IsNil, check.Commentf("unable to load client certificate and key"))
	tlsConfig.Certificates = append(tlsConfig.Certificates, cert)

	conn, err = tls.Dial("tcp", "127.0.0.1:4443", tlsConfig)
	c.Assert(err, checker.NotNil, check.Commentf("should not be allowed to connect to server"))
}
开发者ID:vdemeester,项目名称:traefik,代码行数:56,代码来源:https_test.go


示例7: TestServerUpdateHTTPS

func (s *ServerSuite) TestServerUpdateHTTPS(c *C) {
	var req *http.Request
	e := testutils.NewHandler(func(w http.ResponseWriter, r *http.Request) {
		req = r
		w.Write([]byte("hi https"))
	})
	defer e.Close()

	b := MakeBatch(Batch{
		Addr:     "localhost:41000",
		Route:    `Path("/")`,
		URL:      e.URL,
		Protocol: engine.HTTPS,
		KeyPair:  &engine.KeyPair{Key: localhostKey, Cert: localhostCert},
	})

	b.L.Settings = &engine.HTTPSListenerSettings{TLS: engine.TLSSettings{MinVersion: "VersionTLS11"}}
	c.Assert(s.mux.UpsertHost(b.H), IsNil)
	c.Assert(s.mux.UpsertServer(b.BK, b.S), IsNil)
	c.Assert(s.mux.UpsertFrontend(b.F), IsNil)
	c.Assert(s.mux.UpsertListener(b.L), IsNil)

	c.Assert(s.mux.Start(), IsNil)

	config := &tls.Config{
		InsecureSkipVerify: true,
		// We only support tls 10
		MinVersion: tls.VersionTLS10,
		MaxVersion: tls.VersionTLS10,
	}

	conn, err := tls.Dial("tcp", b.L.Address.Address, config)
	c.Assert(err, NotNil) // we got TLS error

	// Relax the version
	b.L.Settings = &engine.HTTPSListenerSettings{TLS: engine.TLSSettings{MinVersion: "VersionTLS10"}}
	c.Assert(s.mux.UpsertListener(b.L), IsNil)

	time.Sleep(20 * time.Millisecond)

	conn, err = tls.Dial("tcp", b.L.Address.Address, config)
	c.Assert(err, IsNil)

	fmt.Fprintf(conn, "GET / HTTP/1.0\r\n\r\n")
	status, err := bufio.NewReader(conn).ReadString('\n')

	c.Assert(status, Equals, "HTTP/1.0 200 OK\r\n")
	state := conn.ConnectionState()
	c.Assert(state.Version, DeepEquals, uint16(tls.VersionTLS10))
	conn.Close()
}
开发者ID:vnadgir-ef,项目名称:vulcand,代码行数:51,代码来源:mux_test.go


示例8: main

func main() {
	config := &tls.Config{nil, nil, []tls.Certificate{}, nil, nil, "google.com", false}

	// config.Rand = nil
	// config.Time = nil
	// config.Certificates = nil
	// config.RootCAs = nil
	// config.NextProtos = nil
	// config.ServerName = "google.com"
	// config.AuthenticateClient = false
	// config.CipherSuites = nil  // Docs wrong?

	conn, err := tls.Dial("tcp", "google.com:443", config)
	if err != nil {
		fmt.Printf("Error: %v\n", err)
	} else {
		buf := make([]uint8, 100)
		fmt.Printf("Reading...\n")
		fmt.Printf("Hangs :-\\\n")
		size, err := conn.Read(buf) // Hangs
		fmt.Printf("Done reading\n")
		if err != nil {
			fmt.Printf("Error: %v\n", err)
		} else {
			fmt.Printf("Data: %v\n", buf[:size])
		}
	}
}
开发者ID:sbhackerspace,项目名称:sbhx-snippets,代码行数:28,代码来源:https.go


示例9: Dial

/*
Dial opens a new client connection to a Web Socket.

A trivial example client:

	package main

	import (
		"websocket"
		"strings"
	)

	func main() {
	 	ws, err := websocket.Dial("ws://localhost/ws", "", "http://localhost/");
	 	if err != nil {
			panic("Dial: " + err.String())
		}
		if _, err := ws.Write([]byte("hello, world!\n")); err != nil {
			panic("Write: " + err.String())
		}
		var msg = make([]byte, 512);
		if n, err := ws.Read(msg); err != nil {
			panic("Read: " + err.String())
		}
		// use msg[0:n]
	}
*/
func Dial(url, protocol, origin string) (ws *Conn, err os.Error) {
	var client net.Conn

	parsedUrl, err := http.ParseURL(url)
	if err != nil {
		goto Error
	}

	switch parsedUrl.Scheme {
	case "ws":
		client, err = net.Dial("tcp", "", parsedUrl.Host)

	case "wss":
		client, err = tls.Dial("tcp", "", parsedUrl.Host)

	default:
		err = ErrBadScheme
	}
	if err != nil {
		goto Error
	}

	ws, err = newClient(parsedUrl.RawPath, parsedUrl.Host, origin, url, protocol, client, handshake)
	if err != nil {
		goto Error
	}
	return

Error:
	return nil, &DialError{url, protocol, origin, err}
}
开发者ID:GNA-SERVICES-INC,项目名称:MoNGate,代码行数:58,代码来源:client.go


示例10: TestTransportDoubleCloseOnWriteError

// golang.org/issue/13924
// This used to fail after many iterations, especially with -race:
// go test -v -run=TestTransportDoubleCloseOnWriteError -count=500 -race
func TestTransportDoubleCloseOnWriteError(t *testing.T) {
	var (
		mu   sync.Mutex
		conn net.Conn // to close if set
	)

	st := newServerTester(t,
		func(w http.ResponseWriter, r *http.Request) {
			mu.Lock()
			defer mu.Unlock()
			if conn != nil {
				conn.Close()
			}
		},
		optOnlyServer,
	)
	defer st.Close()

	tr := &Transport{
		TLSClientConfig: tlsConfigInsecure,
		DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) {
			tc, err := tls.Dial(network, addr, cfg)
			if err != nil {
				return nil, err
			}
			mu.Lock()
			defer mu.Unlock()
			conn = tc
			return tc, nil
		},
	}
	defer tr.CloseIdleConnections()
	c := &http.Client{Transport: tr}
	c.Get(st.ts.URL)
}
开发者ID:ZhuHangpeng,项目名称:mig,代码行数:38,代码来源:transport_test.go


示例11: TestTransportDisableKeepAlives_Concurrency

// Test concurrent requests with Transport.DisableKeepAlives. We can share connections,
// but when things are totally idle, it still needs to close.
func TestTransportDisableKeepAlives_Concurrency(t *testing.T) {
	const D = 25 * time.Millisecond
	st := newServerTester(t,
		func(w http.ResponseWriter, r *http.Request) {
			time.Sleep(D)
			io.WriteString(w, "hi")
		},
		optOnlyServer,
	)
	defer st.Close()

	var dials int32
	var conns sync.WaitGroup
	tr := &Transport{
		t1: &http.Transport{
			DisableKeepAlives: true,
		},
		TLSClientConfig: tlsConfigInsecure,
		DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) {
			tc, err := tls.Dial(network, addr, cfg)
			if err != nil {
				return nil, err
			}
			atomic.AddInt32(&dials, 1)
			conns.Add(1)
			return &noteCloseConn{Conn: tc, closefn: func() { conns.Done() }}, nil
		},
	}
	c := &http.Client{Transport: tr}
	var reqs sync.WaitGroup
	const N = 20
	for i := 0; i < N; i++ {
		reqs.Add(1)
		if i == N-1 {
			// For the final request, try to make all the
			// others close. This isn't verified in the
			// count, other than the Log statement, since
			// it's so timing dependent. This test is
			// really to make sure we don't interrupt a
			// valid request.
			time.Sleep(D * 2)
		}
		go func() {
			defer reqs.Done()
			res, err := c.Get(st.ts.URL)
			if err != nil {
				t.Error(err)
				return
			}
			if _, err := ioutil.ReadAll(res.Body); err != nil {
				t.Error(err)
				return
			}
			res.Body.Close()
		}()
	}
	reqs.Wait()
	conns.Wait()
	t.Logf("did %d dials, %d requests", atomic.LoadInt32(&dials), N)
}
开发者ID:ZhuHangpeng,项目名称:mig,代码行数:62,代码来源:transport_test.go


示例12: dialHTTP

func dialHTTP(hoststring string, scheme string) (cc *http.ClientConn, err os.Error) {
	host, port, err := net.SplitHostPort(hoststring)
	if err != nil {
		return
	}
	if port == "" {
		switch scheme {
		case "http":
			port = "80"
		case "https":
			port = "80"
		case "riak":
			port = "8098"
		default:
			err = os.NewError("Unknown scheme")
		}
	}
	if err != nil {
		return
	}
	var c net.Conn
	switch scheme {
	case "https":
		c, err = tls.Dial("tcp", host+":"+port, nil)
	default:
		c, err = net.Dial("tcp", host+":"+port)
	}
	if err == nil {
		cc = http.NewClientConn(c, nil)
	}
	return
}
开发者ID:abneptis,项目名称:riak,代码行数:32,代码来源:client.go


示例13: newConn

func newConn(url *url.URL) (*httputil.ClientConn, error) {
	addr := url.Host
	if !hasPort(addr) {
		addr += ":" + url.Scheme
	}
	var conn net.Conn
	var err error
	if url.Scheme == "http" {
		conn, err = net.Dial("tcp", addr)
		if err != nil {
			return nil, err
		}
	} else { // https
		conn, err = tls.Dial("tcp", addr, nil)
		if err != nil {
			return nil, err
		}
		h := url.Host
		if hasPort(h) {
			h = h[0:strings.LastIndex(h, ":")]
		}
		if err := conn.(*tls.Conn).VerifyHostname(h); err != nil {
			return nil, err
		}
	}

	return httputil.NewClientConn(conn, nil), nil
}
开发者ID:codeforsystemsbiology,项目名称:httplib.go,代码行数:28,代码来源:httplib.go


示例14: Dial

// Dial initiates a TLS connection to an outbound server. It returns a
// TLS connection to the server.
func Dial(address string, tr *Transport) (*tls.Conn, error) {
	host, _, err := net.SplitHostPort(address)
	if err != nil {
		// Assume address is a hostname, and that it should
		// use the HTTPS port number.
		host = address
		address = net.JoinHostPort(address, "443")
	}

	cfg, err := tr.TLSClientAuthClientConfig(host)
	if err != nil {
		return nil, err
	}

	conn, err := tls.Dial("tcp", address, cfg)
	if err != nil {
		return nil, err
	}

	state := conn.ConnectionState()
	if len(state.VerifiedChains) == 0 {
		return nil, errors.New(errors.CertificateError, errors.VerifyFailed)
	}

	for _, chain := range state.VerifiedChains {
		for _, cert := range chain {
			revoked, ok := revoke.VerifyCertificate(cert)
			if (!tr.RevokeSoftFail && !ok) || revoked {
				return nil, errors.New(errors.CertificateError, errors.VerifyFailed)
			}
		}
	}

	return conn, nil
}
开发者ID:jfrazelle,项目名称:cfssl,代码行数:37,代码来源:client.go


示例15: connect

func (f *forwarder) connect() {
	if f.c != nil {
		return
	}

	rate := time.Tick(200 * time.Millisecond)
	for {
		var c net.Conn
		var err error

		if f.Config.TlsConfig != nil {
			c, err = tls.Dial("tcp", f.Config.ForwardDest, f.Config.TlsConfig)
		} else {
			c, err = net.DialTimeout("tcp", f.Config.ForwardDest, f.Config.ForwardDestConnectTimeout)
		}

		if err != nil {
			f.cErrors.Inc(1)
			log.WithFields(log.Fields{"id": f.ID, "message": err}).Error("Forwarder Connection Error")
			f.disconnect()
		} else {
			f.cSuccesses.Inc(1)
			log.WithFields(log.Fields{"id": f.ID, "remote_addr": c.RemoteAddr().String()}).Info("Forwarder Connection Success")
			f.c = c
			return
		}
		<-rate
	}
}
开发者ID:heroku,项目名称:log-iss,代码行数:29,代码来源:forwarder.go


示例16: dial

// dial connects to the smtp server with the request encryption type
func dial(host string, port string, encryption encryption, config *tls.Config) (*smtp.Client, error) {
	var conn net.Conn
	var err error

	address := host + ":" + port

	// do the actual dial
	switch encryption {
	case EncryptionSSL:
		conn, err = tls.Dial("tcp", address, config)
	default:
		conn, err = net.Dial("tcp", address)
	}

	if err != nil {
		return nil, errors.New("Mail Error on dailing with encryption type " + encryption.String() + ": " + err.Error())
	}

	c, err := smtp.NewClient(conn, host)

	if err != nil {
		return nil, errors.New("Mail Error on smtp dial: " + err.Error())
	}

	return c, err
}
开发者ID:dulumao,项目名称:mail-1,代码行数:27,代码来源:mail.go


示例17: DialConfig

// DialConfig opens a new client connection to a WebSocket with a config.
func DialConfig(config *Config) (ws *Conn, err error) {
	var client net.Conn
	if config.Location == nil {
		return nil, &DialError{config, ErrBadWebSocketLocation}
	}
	if config.Origin == nil {
		return nil, &DialError{config, ErrBadWebSocketOrigin}
	}
	switch config.Location.Scheme {
	case "ws":
		client, err = net.Dial("tcp", parseAuthority(config.Location))

	case "wss":
		client, err = tls.Dial("tcp", parseAuthority(config.Location), config.TlsConfig)

	default:
		err = ErrBadScheme
	}
	if err != nil {
		goto Error
	}

	ws, err = NewClient(config, client)
	if err != nil {
		client.Close()
		goto Error
	}
	return

Error:
	return nil, &DialError{config, err}
}
开发者ID:fanatic,项目名称:net,代码行数:33,代码来源:client.go


示例18: connectToSMTPServer

func connectToSMTPServer() (net.Conn, *model.AppError) {
	host, _, _ := net.SplitHostPort(Cfg.EmailSettings.SMTPServer)

	var conn net.Conn
	var err error

	if Cfg.EmailSettings.UseTLS {
		tlsconfig := &tls.Config{
			InsecureSkipVerify: true,
			ServerName:         host,
		}

		conn, err = tls.Dial("tcp", Cfg.EmailSettings.SMTPServer, tlsconfig)
		if err != nil {
			return nil, model.NewAppError("SendMail", "Failed to open TLS connection", err.Error())
		}
	} else {
		conn, err = net.Dial("tcp", Cfg.EmailSettings.SMTPServer)
		if err != nil {
			return nil, model.NewAppError("SendMail", "Failed to open connection", err.Error())
		}
	}

	return conn, nil
}
开发者ID:netroby,项目名称:platform,代码行数:25,代码来源:mail.go


示例19: main

func main() {
	addr := flag.String("addr", "", "Address in form of host:port")
	flag.Parse()
	conn, err := tls.Dial("tcp", *addr, &tls.Config{
		InsecureSkipVerify: true,
	})
	if err != nil {
		panic("failed to connect: " + err.Error())
	}
	var nativeChain []certMeta
	chain := conn.ConnectionState().PeerCertificates
	err, root := findRoot(chain)
	if err != nil {
		fmt.Println(err)
	}
	buildNativeChain(chain, root, &nativeChain, len(chain))

	verifyPositions(nativeChain)
	fmt.Printf("%+v\n", nativeChain)
	// for _, cert := range chain {
	// 	fmt.Printf("Certificate: %s, Issued by: %s, Expires at:  %s, Days left: %d\n",
	// 		cert.Subject.CommonName, cert.Issuer.CommonName, cert.NotAfter, cert.NotAfter.Sub(time.Now())/time.Hour/24)
	// }

	conn.Close()
}
开发者ID:artyomtkachenko,项目名称:spikes,代码行数:26,代码来源:certs.go


示例20: MgoDialInfoTls

// MgoDialInfoTls returns a DialInfo suitable
// for dialling an MgoInstance at any of the
// given addresses, optionally using TLS.
func MgoDialInfoTls(useTls bool, addrs ...string) *mgo.DialInfo {
	var dial func(addr net.Addr) (net.Conn, error)
	if useTls {
		pool := x509.NewCertPool()
		xcert, err := cert.ParseCert(CACert)
		if err != nil {
			panic(err)
		}
		pool.AddCert(xcert)
		tlsConfig := &tls.Config{
			RootCAs:    pool,
			ServerName: "anything",
		}
		dial = func(addr net.Addr) (net.Conn, error) {
			conn, err := tls.Dial("tcp", addr.String(), tlsConfig)
			if err != nil {
				logger.Debugf("tls.Dial(%s) failed with %v", addr, err)
				return nil, err
			}
			return conn, nil
		}
	} else {
		dial = func(addr net.Addr) (net.Conn, error) {
			conn, err := net.Dial("tcp", addr.String())
			if err != nil {
				logger.Debugf("net.Dial(%s) failed with %v", addr, err)
				return nil, err
			}
			return conn, nil
		}
	}
	return &mgo.DialInfo{Addrs: addrs, Dial: dial, Timeout: mgoDialTimeout}
}
开发者ID:jkary,项目名称:core,代码行数:36,代码来源:mgo.go



注:本文中的crypto/tls.Dial函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang tls.DialWithDialer函数代码示例发布时间:2022-05-24
下一篇:
Golang tls.Client函数代码示例发布时间:2022-05-24
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap