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

Golang tls.Listen函数代码示例

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

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



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

示例1: newServer

// newServer returns a new instance of the server struct.
func newServer(listenAddrs []string) (*server, error) {
	login := cfg.Username + ":" + cfg.Password
	auth := "Basic " + base64.StdEncoding.EncodeToString([]byte(login))
	s := server{
		authsha: sha256.Sum256([]byte(auth)),
	}

	// Check for existence of cert file and key file
	if !fileExists(cfg.RPCKey) && !fileExists(cfg.RPCCert) {
		// if both files do not exist, we generate them.
		err := genCertPair(cfg.RPCCert, cfg.RPCKey)
		if err != nil {
			return nil, err
		}
	}
	keypair, err := tls.LoadX509KeyPair(cfg.RPCCert, cfg.RPCKey)
	if err != nil {
		return nil, err
	}

	tlsConfig := tls.Config{
		Certificates: []tls.Certificate{keypair},
	}

	ipv4ListenAddrs, ipv6ListenAddrs, err := parseListeners(listenAddrs)
	listeners := make([]net.Listener, 0,
		len(ipv6ListenAddrs)+len(ipv4ListenAddrs))
	for _, addr := range ipv4ListenAddrs {
		listener, err := tls.Listen("tcp4", addr, &tlsConfig)
		if err != nil {
			log.Warnf("RPCS: Can't listen on %s: %v", addr,
				err)
			continue
		}
		listeners = append(listeners, listener)
	}

	for _, addr := range ipv6ListenAddrs {
		listener, err := tls.Listen("tcp6", addr, &tlsConfig)
		if err != nil {
			log.Warnf("RPCS: Can't listen on %s: %v", addr,
				err)
			continue
		}
		listeners = append(listeners, listener)
	}
	if len(listeners) == 0 {
		return nil, errors.New("no valid listen address")
	}

	s.listeners = listeners

	return &s, nil
}
开发者ID:GeertJohan,项目名称:btcwallet,代码行数:55,代码来源:sockets.go


示例2: generateListener

func generateListener(l net.Listener) (net.Listener, error) {
	targetPort := fmt.Sprintf("%s:%d", config.ListenAddress, config.ListenPort)

	if config.HttpServerOptions.UseSSL {
		log.WithFields(logrus.Fields{
			"prefix": "main",
		}).Info("--> Using SSL (https)")
		certs := make([]tls.Certificate, len(config.HttpServerOptions.Certificates))
		certNameMap := make(map[string]*tls.Certificate)
		for i, certData := range config.HttpServerOptions.Certificates {
			cert, err := tls.LoadX509KeyPair(certData.CertFile, certData.KeyFile)
			if err != nil {
				log.WithFields(logrus.Fields{
					"prefix": "main",
				}).Fatalf("Server error: loadkeys: %s", err)
			}
			certs[i] = cert
			certNameMap[certData.Name] = &certs[i]
		}

		config := tls.Config{
			Certificates:      certs,
			NameToCertificate: certNameMap,
			ServerName:        config.HttpServerOptions.ServerName,
			MinVersion:        config.HttpServerOptions.MinVersion,
		}
		return tls.Listen("tcp", targetPort, &config)

	} else if config.HttpServerOptions.UseLE_SSL {

		log.WithFields(logrus.Fields{
			"prefix": "main",
		}).Info("--> Using SSL LE (https)")

		GetLEState(&LE_MANAGER)

		config := tls.Config{
			GetCertificate: LE_MANAGER.GetCertificate,
		}
		return tls.Listen("tcp", targetPort, &config)

	} else {
		log.WithFields(logrus.Fields{
			"prefix": "main",
		}).Info("--> Standard listener (http)")
		return net.Listen("tcp", targetPort)
	}
}
开发者ID:TykTechnologies,项目名称:tyk,代码行数:48,代码来源:main.go


示例3: NewTLSListener

func NewTLSListener(contextName string, address string, tlsListenerConfig config.TLSListenerConfig, envelopeChan chan *events.Envelope, logger *gosteno.Logger) (Listener, error) {
	tlsConfig, err := NewTLSConfig(tlsListenerConfig.CertFile, tlsListenerConfig.KeyFile, tlsListenerConfig.CAFile)
	if err != nil {
		return nil, err
	}

	listener, err := tls.Listen("tcp", address, tlsConfig)
	if err != nil {
		return nil, err
	}

	return &TLSListener{
		listener:       listener,
		envelopeChan:   envelopeChan,
		logger:         logger,
		connections:    make(map[net.Conn]struct{}),
		unmarshaller:   dropsonde_unmarshaller.NewDropsondeUnmarshaller(logger),
		stopped:        make(chan struct{}),
		listenerClosed: make(chan struct{}),

		receivedMessageCountMetricName: contextName + ".receivedMessageCount",
		receivedByteCountMetricName:    contextName + ".receivedByteCount",
		receiveErrorCountMetricName:    contextName + ".receiveErrorCount",
	}, nil
}
开发者ID:sunatthegilddotcom,项目名称:loggregator,代码行数:25,代码来源:tls_listener.go


示例4: serveHTTP

func serveHTTP() {
	parsedAddr := fmt.Sprintf("%s:%d", host, port)
	if development {
		log.Println("Listening for WebSocket connections without TLS on " + parsedAddr)
		log.Fatal(http.ListenAndServe(parsedAddr, nil))
		return
	}
	// Requires cert.pem and cert.key to be present. See cert_setup.sh
	log.Println("Listening for WebSocket connections with TLS on " + parsedAddr)
	certificate, err := tls.X509KeyPair(
		[]byte(os.Getenv("WS_CERT")),
		[]byte(os.Getenv("WS_KEY")),
	)
	if err != nil {
		log.Fatal(err)
	}
	listener, err := tls.Listen(
		"tcp",
		parsedAddr,
		&tls.Config{Certificates: []tls.Certificate{certificate}},
	)
	if err != nil {
		log.Fatal(err)
	}
	log.Fatal(http.Serve(listener, nil))
}
开发者ID:codequest-eu,项目名称:octopussy,代码行数:26,代码来源:ws.go


示例5: startHttp

func startHttp() {
	http.HandleFunc("/register", register)
	http.HandleFunc("/unregister", unregister)
	laddr := fmt.Sprintf(":%d", *port)

	tlsConfig := tlsdefaults.Server()
	_, _, err := keyman.StoredPKAndCert(PKFile, CertFile, "Lantern", "localhost")
	if err != nil {
		log.Fatalf("Unable to initialize private key and certificate: %v", err)
	}
	cert, err := tls.LoadX509KeyPair(CertFile, PKFile)
	if err != nil {
		log.Fatalf("Unable to load certificate and key from %s and %s: %s", CertFile, PKFile, err)
	}
	tlsConfig.Certificates = []tls.Certificate{cert}

	log.Debugf("About to listen at %v", laddr)
	l, err := tls.Listen("tcp", laddr, tlsConfig)
	if err != nil {
		log.Fatalf("Unable to listen for tls connections at %s: %s", laddr, err)
	}

	log.Debug("About to serve")
	err = http.Serve(l, nil)
	if err != nil {
		log.Fatalf("Unable to serve: %s", err)
	}
}
开发者ID:2722,项目名称:lantern,代码行数:28,代码来源:web.go


示例6: SetupTCP

func SetupTCP(useTls bool, address string) {
	println("Setting Up TCP at:", address)
	const connectedAndWaitingMax = 0
	conChan := make(chan net.Conn, connectedAndWaitingMax)
	halt := make(chan int)

	var listener net.Listener
	var err os.Error
	if useTls {
		certs := make([]tls.Certificate, 1)
		c0, errx := tls.LoadX509KeyPair("cert/cert.pem", "cert/key.pem")
		certs[0] = c0
		fmt.Println(errx)
		config := tls.Config{Certificates: certs, ServerName: "TestServer"}
		listener, err = tls.Listen("tcp", ":6666", &config)
		println("TLS")
	} else {
		listener, err = net.Listen("tcp", ":6666")
		println("TCP")
	}

	if err != nil {
		println(err)
	}

	go getConnections(listener, conChan, halt)

	conChan2 := make(chan *LoggedIn, connectedAndWaitingMax)

	go welcomTestLoop(conChan, conChan2)
	go updateLoop(conChan2)

	println("TCP Setup")

}
开发者ID:Craig-Macomber,项目名称:Go-MMO-Panda,代码行数:35,代码来源:control.go


示例7: run

func (s *Server) run(addrString string) {
	restLogger.Info("Starting REST API on ", addrString)
	if s.snapTLS != nil {
		cer, err := tls.LoadX509KeyPair(s.snapTLS.cert, s.snapTLS.key)
		if err != nil {
			s.err <- err
			return
		}
		config := &tls.Config{Certificates: []tls.Certificate{cer}}
		ln, err := tls.Listen("tcp", addrString, config)
		if err != nil {
			s.err <- err
		}
		s.serverListener = ln
		s.wg.Add(1)
		go s.serveTLS(ln)
	} else {
		ln, err := net.Listen("tcp", addrString)
		if err != nil {
			s.err <- err
		}
		s.serverListener = ln
		s.addr = ln.Addr()
		s.wg.Add(1)
		go s.serve(ln)
	}
}
开发者ID:IRCody,项目名称:snap,代码行数:27,代码来源:server.go


示例8: main

func main() {
	cert, err := tls.LoadX509KeyPair("server.crt", "server.key")
	if err != nil {
		log.Fatalf("server : loadkeys :%s", err)
	}
	config := tls.Config{Certificates: []tls.Certificate{cert}}
	config.Time = time.Now
	config.Rand = rand.Reader

	service := "127.0.0.1:10000"
	listener, err := tls.Listen("tcp", service, &config)
	if err != nil {
		log.Fatalf("server : listen: %s", err)
	}
	log.Print("server: listening")
	for {
		conn, err := listener.Accept()
		if err != nil {
			log.Panicf("server:accept :%s", err)
			break
		}
		log.Printf("server : accepted from %s", conn.RemoteAddr())
		go handleClient(conn)
	}
}
开发者ID:wmydz1,项目名称:https,代码行数:25,代码来源:httpsserver.go


示例9: Start

func (s *server) Start() error {
	var l net.Listener
	var err error

	if s.opts.EnableTLS && s.opts.TLSConfig != nil {
		l, err = tls.Listen("tcp", s.address, s.opts.TLSConfig)
	} else {
		l, err = net.Listen("tcp", s.address)
	}
	if err != nil {
		return err
	}

	log.Infof("Listening on %s", l.Addr().String())

	s.mtx.Lock()
	s.address = l.Addr().String()
	s.mtx.Unlock()

	go http.Serve(l, s.mux)

	go func() {
		ch := <-s.exit
		ch <- l.Close()
	}()

	return nil
}
开发者ID:zhangpeihao,项目名称:micro,代码行数:28,代码来源:server.go


示例10: startServingTLS

// startServingTLS creates and registers a secure listener and begins serving traffic.
func (s *TestHttpService) startServingTLS(addr string, cert []byte, key []byte, caCert []byte, handler *http.ServeMux) error {
	tlsCert, err := tls.X509KeyPair(append(cert, caCert...), key)

	if err != nil {
		return err
	}

	cfg := &tls.Config{
		Certificates: []tls.Certificate{tlsCert},
	}

	listener, err := tls.Listen("tcp", addr, cfg)

	if err != nil {
		return err
	}

	s.listeners = append(s.listeners, listener)
	fmt.Printf("Started, serving TLS at %s\n", listener.Addr().String())

	go func() {
		err := http.Serve(listener, handler)

		if err != nil {
			fmt.Printf("Server message: %v", err)
		}
	}()

	return nil
}
开发者ID:asiainfoLDP,项目名称:datafactory,代码行数:31,代码来源:router_http_server.go


示例11: NewServer

/*
NewServer returns a server that listens on a TCP socket protected by
TLS, and automatically starts that server.
*/
func NewServer(address string, handler protocol.ConnectionHandlerFunc) (retServer *server, err error) {
	cert, err := Asset("self-signed.cert")
	if err != nil {
		return nil, err
	}

	key, err := Asset("self-signed.key")
	if err != nil {
		return nil, err
	}

	serverCert, err := tls.X509KeyPair(cert, key)
	if err != nil {
		return nil, err
	}

	serverTLSConf := &tls.Config{
		Certificates: []tls.Certificate{serverCert},
	}

	socket, err := tls.Listen("tcp", address, serverTLSConf)
	if err != nil {
		return
	}

	retServer = &server{
		s:       socket,
		handler: handler,
	}

	go retServer.listen()
	return
}
开发者ID:nathanpalmer,项目名称:hologram,代码行数:37,代码来源:server.go


示例12: listenWithCert

func listenWithCert(hostname string, address string) {

	listening.Add(1)
	go func() {
		log.Println("DEBUG - start mock server ..")
		// Establish a dummy TLS server
		var serverConfig tls.Config
		kp := makeCert(hostname)

		serverConfig.Certificates = []tls.Certificate{kp}

		listener, err := tls.Listen("tcp", address, &serverConfig)
		if err != nil {
			panic(err)
		}
		// Listen and handshake for a single connection
		defer listener.Close()
		listening.Done()

		conn, err := listener.Accept()
		if err != nil {
			panic(err)
		}
		defer conn.Close()
		tlsconn, ok := conn.(*tls.Conn)
		if !ok {
			panic("conn should of *tls.Conn")
		}
		if err := tlsconn.Handshake(); err != nil {
			return
		}
	}()
	listening.Wait()
}
开发者ID:EverythingMe,项目名称:logstash-forwarder,代码行数:34,代码来源:publisher1_test.go


示例13: Server

func Server() {
	host := config.Interface + ":" + config.Port
	cert, err := tls.LoadX509KeyPair("./certs/localhost1437319773023.pem", "./certs/localhost1437319773023.key")
	if err != nil {
		panic(err)
	}
	config := tls.Config{Certificates: []tls.Certificate{cert}, NextProtos: []string{"h2", "h2-14"}}
	listener, err := tls.Listen("tcp", host, &config)
	fmt.Println("Listening on https://" + host)
	fmt.Println("setInterval(function() { $.get('https://" + host + "') }, 750)")

	if err != nil {
		panic(err)
	}

	for {
		conn, err := listener.Accept()

		if err != nil {
			panic(err)
		}
		proto := conn.(*tls.Conn).ConnectionState().NegotiatedProtocol
		log.Println("Negotiated proto", proto)

		if err != nil {
			log.Printf("server: accept: %s", err)
			break
		}
		log.Printf("server: accepted from %s", conn.RemoteAddr())
		replay.TruncateFile()
		FuzzConnection(conn)
	}
}
开发者ID:johnso51,项目名称:http2fuzz,代码行数:33,代码来源:server.go


示例14: Listen

// Start network server
func (s *Server) Listen() error {
	tlsConfig, err := crypto.GetServerTlsConfig()
	if err != nil {
		return err
	}

	var listener net.Listener
	if tlsConfig != nil {
		listener, err = tls.Listen("tcp", s.address, tlsConfig)
	} else {
		listener, err = net.Listen("tcp", s.address)
		log.Println("Warning: creating a non-TLS insecure server")
	}
	if err != nil {
		return err
	}

	defer listener.Close()

	for {
		conn, err := listener.Accept()
		if err != nil {
			return err
		}

		s.newClient(conn)
	}

	return nil
}
开发者ID:emersion,项目名称:miko,代码行数:31,代码来源:server.go


示例15: Listen

// Start a `how` server listening for connections at `addr`. You need to call Accept() on the
// returned socket to start accepting connections. `how` and `addr` are passed to `net.Listen()`
// and thus any values accepted by net.Listen are valid.
// The returned server has Handlers=DefaultHandlers and Limits=DefaultLimits set.
func Listen(how, addr string, config *tls.Config) (*Server, error) {

	l, err := tls.Listen(how, addr, config)

	if err != nil {
		return nil, err
	}

	if tcpl, ok := l.(*net.TCPListener); ok {
		// Wrap TCP listener to enable TCP keep-alive
		l = &tcpKeepAliveListener{tcpl}
	}

	s := NewServer(DefaultHandlers, DefaultLimits, l)

	if how == "unix" || how == "unixpacket" {
		// Unix sockets must be unlink()ed before being reused again.
		// Handle common process-killing signals so we can gracefully shut down.
		sigc := make(chan os.Signal, 1)
		signal.Notify(sigc, os.Interrupt, os.Kill, syscall.SIGTERM)
		go func(c chan os.Signal) {
			<-c // Wait for a signal
			//sig := <-c  // Wait for a signal
			//log.Printf("Caught signal %s: shutting down.", sig)
			s.Close() // Stop listening and unlink the socket
			os.Exit(0)
		}(sigc)
	}

	return s, nil
}
开发者ID:Yossibh,项目名称:envdb,代码行数:35,代码来源:server.go


示例16: startSsl

func (self *HttpServer) startSsl(p *pat.PatternServeMux) {
	defer func() { self.shutdown <- true }()

	// return if the ssl port or cert weren't set
	if self.httpSslPort == "" || self.httpSslCert == "" {
		return
	}

	log.Info("Starting SSL api on port %s using certificate in %s", self.httpSslPort, self.httpSslCert)

	cert, err := tls.LoadX509KeyPair(self.httpSslCert, self.httpSslCert)
	if err != nil {
		panic(err)
	}

	self.sslConn, err = tls.Listen("tcp", self.httpSslPort, &tls.Config{
		Certificates: []tls.Certificate{cert},
	})
	if err != nil {
		panic(err)
	}

	if err := libhttp.Serve(self.sslConn, p); err != nil && !strings.Contains(err.Error(), "closed network") {
		panic(err)
	}
}
开发者ID:johntdyer,项目名称:golang-devops-stuff,代码行数:26,代码来源:api.go


示例17: main

func main() {
	random, _ := os.Open("/dev/urandom", os.O_RDONLY, 0)
	pembytes := readEntireFile("/home/kris/SSL/gr0g.crt")
	cert, _ := pem.Decode(pembytes)
	keybytes := readEntireFile("/home/kris/SSL/gr0g.key")
	pk, _ := pem.Decode(keybytes)

	privatekey, _ := x509.ParsePKCS1PrivateKey(pk.Bytes)

	config := new(tls.Config)
	config.Certificates = make([]tls.Certificate, 1)
	config.Certificates[0].Certificate = [][]byte{cert.Bytes}
	config.Certificates[0].PrivateKey = privatekey
	config.Rand = random
	//config.RootCAs = caset
	config.Time = time.Seconds
	listener, err := tls.Listen("tcp", "0.0.0.0:8443", config)

	fmt.Printf("%s\n", err)
	for {
		conn, _ := listener.Accept()
		go func() {
			for {
				buf := make([]byte, 1024)
				_, err := conn.Read(buf)
				if err != nil {
					return
				}
				fmt.Printf("%s", buf)
			}
		}()
	}
}
开发者ID:gr0gmint,项目名称:gocon,代码行数:33,代码来源:sslserver.go


示例18: SecureServe

// SecureListen obtains a listener that accepts
// secure connections
func SecureServe(addr string, certFile, keyFile, caFile string) {
	config := tls.Config{}

	// load the server cert / key
	cert, err := tls.LoadX509KeyPair(certFile, keyFile)
	if err != nil {
		log.Fatalf("%s", err)
	}
	config.Certificates = []tls.Certificate{cert}

	// load the ca if necessary
	// FIXME(alainjobart) this doesn't quite work yet, have
	// to investigate
	if caFile != "" {
		config.ClientCAs = x509.NewCertPool()

		pemCerts, err := ioutil.ReadFile(caFile)
		if err != nil {
			log.Fatalf("%s", err)
		}
		if !config.ClientCAs.AppendCertsFromPEM(pemCerts) {
			log.Fatalf("%s", err)
		}

		config.ClientAuth = tls.RequireAndVerifyClientCert
	}
	l, err := tls.Listen("tcp", addr, &config)
	if err != nil {
		log.Fatalf("%s", err)
	}
	throttled := NewThrottledListener(l, *secureThrottle, *secureMaxBuffer)
	cl := proc.Published(throttled, "SecureConnections", "SecureAccepts")
	go http.Serve(cl, nil)
}
开发者ID:rjammala,项目名称:vitess,代码行数:36,代码来源:secure.go


示例19: Start

func (t *TLSListener) Start() {
	var err error
	listenerClosed := make(chan struct{})

	listener, err := tls.Listen("tcp", t.address, t.config)
	if err != nil {
		t.logger.Fatalf("Failed to start TCP listener. %s", err)
	}

	t.lock.Lock()
	t.connections = make(map[net.Conn]struct{})
	t.stopped = make(chan struct{})
	t.listenerClosed = listenerClosed
	t.listener = listener
	t.lock.Unlock()

	t.logger.Infof("TCP listener listening on %s", t.address)
	for {
		conn, err := t.listener.Accept()
		if err != nil {
			close(listenerClosed)
			t.logger.Debugf("Error while reading: %s", err)
			return
		}
		t.addConnection(conn)
		go t.handleConnection(conn)
	}
}
开发者ID:Jonty,项目名称:loggregator,代码行数:28,代码来源:tls_listener.go


示例20: runServer

func runServer(ch chan bool, done chan bool) {
	cert, err := tls.LoadX509KeyPair("../cert.pem", "../key.pem")
	if err != nil {
		log.Fatalf("While loading tls certs: %v", err)
		return
	}
	config := tls.Config{Certificates: []tls.Certificate{cert}}
	ln, err := tls.Listen("tcp", addr, &config)
	if err != nil {
		log.Fatalf("When listening: %v", err)
		return
	}
	s := rpc.NewServer()
	if err := s.Register(&PostingList{}); err != nil {
		log.Fatalf("Error when registering rpc server: %v", err)
		return
	}

	ch <- true
	log.Debugln("Ready to accept new connection")
	conn, err := ln.Accept()
	if err != nil {
		log.Fatalf("cannot accept incoming tcp conn: %s", err)
		return
	}
	defer conn.Close()
	log.Debugln("Accepted a connection")
	go s.ServeConn(conn)
	<-done
}
开发者ID:dgraph-io,项目名称:experiments,代码行数:30,代码来源:main.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang tls.LoadX509KeyPair函数代码示例发布时间:2022-05-24
下一篇:
Golang tls.DialWithDialer函数代码示例发布时间: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