feat:完善项目

This commit is contained in:
henry
2021-09-28 11:47:19 +08:00
commit da7b3130fe
167 changed files with 456676 additions and 0 deletions

34
rpc/README.md Normal file
View File

@ -0,0 +1,34 @@
## GRPC
### 生成proto
```javasrript
protoc --go_out=plugins=grpc:. *.proto
```
### 完整示例:
```javasrript
protoc --go_out=plugins=grpc,Mfoo/bar.proto=bar,import_prefix=,import_path=foo/bar:. ./*.proto
```
### TLS私钥和公钥
- TLS私钥和公钥
- 制作私钥 (.key)
```sh
openssl genrsa -out server.key 2048
```
```sh
openssl ecparam -genkey -name secp384r1 -out server.key
```
```sh
openssl req -new -x509 -sha256 -key server.key -out server.pem -days 3650
```
```sh
Country Name (2 letter code) [AU]:CN
State or Province Name (full name) [Some-State]:Anhui
Locality Name (eg, city) []:Hefei
Organization Name (eg, company) [Internet Widgits Pty Ltd]:IPEACE.ORG.CN
Organizational Unit Name (eg, section) []:DEVELOPER
Common Name (e.g. server FQDN or YOUR name) []:TOKYO_HOT.RPC
Email Address []:email@ipeace.org.cn
```

24
rpc/client/auth.go Normal file
View File

@ -0,0 +1,24 @@
package client
import "context"
type Auth struct {
isTLS bool
Value string
}
const headerAuthorize string = "authorization"
func (a *Auth) SetIsTLS(status bool) {
a.isTLS = status
}
// GetRequestMetadata 获取当前请求认证所需的元数据
func (a *Auth) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
return map[string]string{headerAuthorize: a.Value}, nil
}
// RequireTransportSecurity 是否需要基于 TLS 认证进行安全传输
func (a *Auth) RequireTransportSecurity() bool {
return a.isTLS
}

View File

@ -0,0 +1,39 @@
package handle
import (
"SciencesServer/rpc/client"
"SciencesServer/rpc/client/proto"
"context"
"google.golang.org/grpc"
)
type Account struct{}
// RegisterHandle register handle
type RegisterHandle func(tenant, uid string) (*proto.RegisterResponse, error)
// Register 注册
func (this *Account) Register() RegisterHandle {
return func(tenant, uid string) (*proto.RegisterResponse, error) {
resp := new(proto.RegisterResponse)
err := client.MQTTServerClient.Handle(func(conn *grpc.ClientConn) error {
var err error
// 初始化客户端
cc := proto.NewAccountHandleClient(conn)
req := &proto.RegisterRequest{
Tenant: tenant, Uid: uid,
}
resp, err = cc.RegisterHandle(context.Background(), req)
return err
}, &client.Auth{Value: "bearer grpc.auth.token"})
return resp, err
}
}
func NewAccountClient() *Account {
return &Account{}
}

View File

@ -0,0 +1,320 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.25.0
// protoc v3.15.5
// source: account.proto
package proto
import (
context "context"
reflect "reflect"
sync "sync"
proto "github.com/golang/protobuf/proto"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
// This is a compile-time assertion that a sufficiently up-to-date version
// of the legacy proto package is being used.
const _ = proto.ProtoPackageIsVersion4
type RegisterRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Tenant string `protobuf:"bytes,1,opt,name=tenant,proto3" json:"tenant,omitempty"`
Uid string `protobuf:"bytes,2,opt,name=uid,proto3" json:"uid,omitempty"`
}
func (x *RegisterRequest) Reset() {
*x = RegisterRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_account_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *RegisterRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RegisterRequest) ProtoMessage() {}
func (x *RegisterRequest) ProtoReflect() protoreflect.Message {
mi := &file_account_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use RegisterRequest.ProtoReflect.Descriptor instead.
func (*RegisterRequest) Descriptor() ([]byte, []int) {
return file_account_proto_rawDescGZIP(), []int{0}
}
func (x *RegisterRequest) GetTenant() string {
if x != nil {
return x.Tenant
}
return ""
}
func (x *RegisterRequest) GetUid() string {
if x != nil {
return x.Uid
}
return ""
}
type RegisterResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Domain string `protobuf:"bytes,1,opt,name=domain,proto3" json:"domain,omitempty"`
Token string `protobuf:"bytes,2,opt,name=token,proto3" json:"token,omitempty"`
}
func (x *RegisterResponse) Reset() {
*x = RegisterResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_account_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *RegisterResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RegisterResponse) ProtoMessage() {}
func (x *RegisterResponse) ProtoReflect() protoreflect.Message {
mi := &file_account_proto_msgTypes[1]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use RegisterResponse.ProtoReflect.Descriptor instead.
func (*RegisterResponse) Descriptor() ([]byte, []int) {
return file_account_proto_rawDescGZIP(), []int{1}
}
func (x *RegisterResponse) GetDomain() string {
if x != nil {
return x.Domain
}
return ""
}
func (x *RegisterResponse) GetToken() string {
if x != nil {
return x.Token
}
return ""
}
var File_account_proto protoreflect.FileDescriptor
var file_account_proto_rawDesc = []byte{
0x0a, 0x0d, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12,
0x05, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x3b, 0x0a, 0x0f, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74,
0x65, 0x72, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x16, 0x0a, 0x06, 0x74, 0x65, 0x6e,
0x61, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x74, 0x65, 0x6e, 0x61, 0x6e,
0x74, 0x12, 0x10, 0x0a, 0x03, 0x75, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03,
0x75, 0x69, 0x64, 0x22, 0x40, 0x0a, 0x10, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x65, 0x72, 0x52,
0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x16, 0x0a, 0x06, 0x64, 0x6f, 0x6d, 0x61, 0x69,
0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x64, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x12,
0x14, 0x0a, 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05,
0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x32, 0x54, 0x0a, 0x0d, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74,
0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x12, 0x43, 0x0a, 0x0e, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74,
0x65, 0x72, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x12, 0x16, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f,
0x2e, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x65, 0x72, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74,
0x1a, 0x17, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x65,
0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x62, 0x06, 0x70, 0x72, 0x6f,
0x74, 0x6f, 0x33,
}
var (
file_account_proto_rawDescOnce sync.Once
file_account_proto_rawDescData = file_account_proto_rawDesc
)
func file_account_proto_rawDescGZIP() []byte {
file_account_proto_rawDescOnce.Do(func() {
file_account_proto_rawDescData = protoimpl.X.CompressGZIP(file_account_proto_rawDescData)
})
return file_account_proto_rawDescData
}
var file_account_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_account_proto_goTypes = []interface{}{
(*RegisterRequest)(nil), // 0: proto.RegisterRequest
(*RegisterResponse)(nil), // 1: proto.RegisterResponse
}
var file_account_proto_depIdxs = []int32{
0, // 0: proto.AccountHandle.RegisterHandle:input_type -> proto.RegisterRequest
1, // 1: proto.AccountHandle.RegisterHandle:output_type -> proto.RegisterResponse
1, // [1:2] is the sub-list for method output_type
0, // [0:1] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_account_proto_init() }
func file_account_proto_init() {
if File_account_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_account_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*RegisterRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_account_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*RegisterResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_account_proto_rawDesc,
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_account_proto_goTypes,
DependencyIndexes: file_account_proto_depIdxs,
MessageInfos: file_account_proto_msgTypes,
}.Build()
File_account_proto = out.File
file_account_proto_rawDesc = nil
file_account_proto_goTypes = nil
file_account_proto_depIdxs = nil
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConnInterface
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion6
// AccountHandleClient is the client API for AccountHandle service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type AccountHandleClient interface {
RegisterHandle(ctx context.Context, in *RegisterRequest, opts ...grpc.CallOption) (*RegisterResponse, error)
}
type accountHandleClient struct {
cc grpc.ClientConnInterface
}
func NewAccountHandleClient(cc grpc.ClientConnInterface) AccountHandleClient {
return &accountHandleClient{cc}
}
func (c *accountHandleClient) RegisterHandle(ctx context.Context, in *RegisterRequest, opts ...grpc.CallOption) (*RegisterResponse, error) {
out := new(RegisterResponse)
err := c.cc.Invoke(ctx, "/proto.AccountHandle/RegisterHandle", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// AccountHandleServer is the server API for AccountHandle service.
type AccountHandleServer interface {
RegisterHandle(context.Context, *RegisterRequest) (*RegisterResponse, error)
}
// UnimplementedAccountHandleServer can be embedded to have forward compatible implementations.
type UnimplementedAccountHandleServer struct {
}
func (*UnimplementedAccountHandleServer) RegisterHandle(context.Context, *RegisterRequest) (*RegisterResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method RegisterHandle not implemented")
}
func RegisterAccountHandleServer(s *grpc.Server, srv AccountHandleServer) {
s.RegisterService(&_AccountHandle_serviceDesc, srv)
}
func _AccountHandle_RegisterHandle_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RegisterRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(AccountHandleServer).RegisterHandle(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/proto.AccountHandle/RegisterHandle",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(AccountHandleServer).RegisterHandle(ctx, req.(*RegisterRequest))
}
return interceptor(ctx, in, info, handler)
}
var _AccountHandle_serviceDesc = grpc.ServiceDesc{
ServiceName: "proto.AccountHandle",
HandlerType: (*AccountHandleServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "RegisterHandle",
Handler: _AccountHandle_RegisterHandle_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "account.proto",
}

92
rpc/client/server.go Normal file
View File

@ -0,0 +1,92 @@
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}
}

1
rpc/serve/server.go Normal file
View File

@ -0,0 +1 @@
package serve