當前位置: 首頁>>代碼示例>>Golang>>正文


Golang tls.Listen函數代碼示例

本文整理匯總了Golang中crypto/tls.Listen函數的典型用法代碼示例。如果您正苦於以下問題:Golang Listen函數的具體用法?Golang Listen怎麽用?Golang Listen使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了Listen函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的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


注:本文中的crypto/tls.Listen函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。