Files
2021-09-28 11:47:19 +08:00

93 lines
2.0 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package client
import (
"context"
"fmt"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/grpclog"
"google.golang.org/grpc"
)
// IServerCredentials IServerCredentials
type IServerCredentials interface {
SetIsTLS(bool)
GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error)
RequireTransportSecurity() bool
}
type Server struct {
Option map[string]*ServerOption
}
// ServerEntity rpc server
type ServerEntity struct {
Address string // 连接地址
Opts []grpc.DialOption // 配置信息
}
type ServerOption struct {
Host string
Port int
IsTLS bool
TLSName, Pem string
}
var (
MQTTServerClient = new(ServerEntity)
)
// InvokeHandler 调用方法
type InvokeHandler func(*grpc.ClientConn) error
// Handle handle
func (c *ServerEntity) Handle(handle InvokeHandler, auth *Auth) error {
c.Opts = append(c.Opts, grpc.WithPerRPCCredentials(auth))
conn, err := grpc.Dial(c.Address, c.Opts...)
defer conn.Close()
if err != nil {
grpclog.Error("GRPC Dial Ping Error%v ", err)
}
return handle(conn)
}
func (s *Server) Register(key string, serverCredentials IServerCredentials) *ServerEntity {
entity := new(ServerEntity)
option, has := s.Option[key]
if !has {
panic("Unknown RPCServer Setting%v" + key)
}
opts := make([]grpc.DialOption, 0)
if option.IsTLS {
creds, err := credentials.NewClientTLSFromFile(option.Pem, option.TLSName)
if err != nil {
grpclog.Fatalf("Failed to create Centre TLS credentials %v", err)
}
opts = append(opts, grpc.WithTransportCredentials(creds))
} else {
opts = append(opts, grpc.WithInsecure())
}
serverCredentials.SetIsTLS(option.IsTLS)
opts = append(opts, grpc.WithPerRPCCredentials(serverCredentials))
entity.Address = fmt.Sprintf("%s:%d", option.Host, option.Port)
entity.Opts = opts
return entity
}
func (s *Server) Run() {
MQTTServerClient = s.Register("MQTT", new(Auth))
}
func NewServer(option map[string]*ServerOption) *Server {
return &Server{Option: option}
}