为什么gRPC服务器示例使用net.Listen而不是tls.Listen?

huangapple go评论75阅读模式
英文:

Why do grpc server examples use net.Listen instead of tls.Listen

问题

我正在设置一个使用TLS进行客户端授权/认证的golang grpc服务器。我看到的所有服务器设置示例都使用net.Listen()而不是tls.Listen()。为什么会这样呢?

import (
    "crypto/tls"
    "github.com/pkg/errors"
    "google.golang.org/grpc"
    "google.golang.org/grpc/credentials"
    "net"
)

func startGRPCListener(hostport string, tlsconfig *tls.Config) (grpcServer *grpc.Server) {
    listener, _ = net.Listen("tcp", hostport)
    cred := grpc.Creds(credentials.NewTLS(tlsconfig))
    grpcServer := grpc.NewServer(cred)
    go func() {
        serveErr := grpcServer.Serve(listener)
        log.WithError(serveErr).Info("GRPC server exited")
    }()    

    return
}

我注意到在一些可工作的示例中,如果我切换到tls.Listen,连接将无法建立。然而,在其他情况下,这并不会引起问题!

我想知道"我应该使用net.Listen还是tls.Listen,或者它们没有区别吗?"

英文:

I'm setting up a golang grpc server that will use TLS for client authorization/authentication. All the examples of server setup that I've seen use net.Listen() instead of tls.Listen(). Why is this?

import (
    "crypto/tls"
    "github.com/pkg/errors"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
    "net"
)

func startGRPCListener(hostport string, tlsconfig *tls.Config) (grpcServer *grpc.Server) {
	listener, _ = net.Listen("tcp", hostport)
	cred := grpc.Creds(credentials.NewTLS(tlsconfig))
	grpcServer := grpc.NewServer(cred)
	go func() {
		serveErr := grpcServer.Serve(listener)
		log.WithError(serveErr).Info("GRPC server exited")
	}()	

	return
}

I've noticed in a couple of working examples if I swap to tls.Listen, the connection can no longer be made. However, in other cases, this doesn't cause a problem!

I guess my question is "should I use net.Listen or tls.Listen, or does it not make a difference?"

答案1

得分: 3

为什么会这样?

因为这些是关于gRPC而不是关于TLS的示例?
示例往往是为了演示某些内容而进行简化的。示例并不是用于生产代码的复制粘贴样本。

英文:

> Why is this?

Because these are examples about grpc and not about TLS?
Examples tend to be examples: Simplifications to demonstrate something. Examples are not copy-paste samples for production code.

huangapple
  • 本文由 发表于 2017年9月1日 03:31:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/45988816.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定