2 Star 3 Fork 1

Allen / go-scaffold

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
connect.go 1.88 KB
一键复制 编辑 原始数据 按行查看 历史
Allen 提交于 2021-08-05 16:34 . update grpc client connect options
package client
import (
"context"
"fmt"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
)
type TokenAuth struct {
Token string
TokenKey string
}
// Return value is mapped to request headers.
func (t TokenAuth) GetRequestMetadata(ctx context.Context, in ...string) (map[string]string, error) {
return map[string]string{
t.TokenKey: t.Token,
}, nil
}
func (TokenAuth) RequireTransportSecurity() bool {
return true
}
// Connector with gRPC dial option
type Connector struct {
Host string
Port int
SSLName string
SSLCrtFile string
// Deadline in seconds
Deadline int
// Token string in headers
Token string
// TokenKey default = "authorization"
TokenKey string
}
// Connect for gRPC client
// those dial option has include in connect
// - WithTransportCredentials if SSLName and SSLCrtFile is valid value
// - WithInsecure if SSLName and SSLCrtFile is empty value
// - WithPerRPCCredentials (Token and custom token key only)
func (c *Connector) Connect(opts ...grpc.DialOption) (*grpc.ClientConn, error) {
// tls config
crtFile := c.SSLCrtFile
sslName := c.SSLName
if crtFile != "" && sslName != "" {
cred, err := credentials.NewClientTLSFromFile(crtFile, sslName)
if err != nil {
return nil, err
}
opts = append(opts, grpc.WithTransportCredentials(cred))
} else {
opts = append(opts, grpc.WithInsecure())
}
// token
if c.Token != "" {
if c.TokenKey == "" {
c.TokenKey = "authorization"
}
opts = append(opts, grpc.WithPerRPCCredentials(TokenAuth{
Token: c.Token,
TokenKey: c.TokenKey,
}))
}
addr := fmt.Sprintf("%s:%d", c.Host, c.Port)
return grpc.Dial(addr, opts...)
}
// ContextWithDeadline TL;DR
func (c *Connector) ContextWithDeadline() (context.Context, context.CancelFunc) {
deadline := time.Now().Add(time.Duration(c.Deadline) * time.Second)
return context.WithDeadline(context.Background(), deadline)
}
Go
1
https://gitee.com/zakums06/go-scaffold.git
git@gitee.com:zakums06/go-scaffold.git
zakums06
go-scaffold
go-scaffold
v1.0.14

搜索帮助