本文整理汇总了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
}
示例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)
}
}
示例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
}
示例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))
}
示例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)
}
}
示例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")
}
示例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)
}
}
示例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)
}
}
示例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
}
示例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
}
示例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
}
示例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()
}
示例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)
}
}
示例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
}
示例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
}