代码拉取完成,页面将自动刷新
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)
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。