我正在编写一些为多个服务生成 grpc tls 凭据的代码,因此我想以模块化的方式编写它,以便它可以通过各种方式接受证书。虽然我觉得代码已经变得意大利面条和困惑。
我的目标是 GetCredentials()
和 GetTls()
能够从不同位置调用和配置的方法,以便为多个服务生成凭据。
我遇到的问题在于 GetCfgCredentials()
和 GetCfgTls()
,我希望他们返回接口(interface),但我得到一个类型错误
Cannot use 'credentials' (type credentials.TransportCredentials) as the type CfgCredentials Type does not implement 'CfgCredentials' as some methods are missing: GetCredentials() *credentials.TransportCredentials
有经验的人可以告诉我他们对我构建下面列出的代码的方式和错误的看法吗?我对此很陌生,并希望获得一些关于如何以最模块化和最灵活的方式创建它的指示。var globalCreds credentials.TransportCredentials
var globalTlsConfig *tls.Config
type CfgCredentialsProvider interface {
GetCredentials() *credentials.TransportCredentials
}
type CfgTlsProvider interface {
GetTlsConfig() *tls.Config
}
type CfgCredentials interface {
CfgCredentialsProvider
}
type CfgTls interface {
CfgTlsProvider
}
func GetGlobalCreds() (credentials.TransportCredentials, error) {
if globalCreds == nil {
creds := credentials.NewTLS(globalTlsConfig)
globalCreds = creds
}
return globalCreds, nil
}
func GetGlobalTls(CertificatePath, PrivateEnhancedMailPath string) (*tls.Config, error) {
serverCert, err := tls.LoadX509KeyPair(CertificatePath, PrivateEnhancedMailPath)
if err != nil {
return nil, err
}
if globalTlsConfig == nil {
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{serverCert},
}
globalTlsConfig = tlsConfig
}
return globalTlsConfig, nil
}
func GetCfgCredentials() (CfgCredentials, bool) {
credentials, err := GetGlobalCreds()
if err != nil {
return nil, false
}
return credentials, true
}
func GetCfgTls(CertificatePath, PrivateEnhancedMailPath string) (CfgTls, bool) {
tls, err := GetGlobalTls(CertificatePath, PrivateEnhancedMailPath)
if err != nil {
return nil, false
}
return tls, true
}
最佳答案
看起来像您看到的错误:Cannot use 'credentials' (type credentials.TransportCredentials) as the type CfgCredentials Type does not implement 'CfgCredentials' as some methods are missing: GetCredentials() *credentials.TransportCredentials
是因为你的类型没有实现接口(interface)。
它需要实现TransportCredentials界面。
关于go - 类型错误返回 grpc tls 凭据的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67622361/