feat: pkg

This commit is contained in:
2022-01-11 00:48:03 +08:00
parent d5714c2c3d
commit 35119f2003
11 changed files with 882 additions and 4 deletions
+51
View File
@@ -0,0 +1,51 @@
package config
import (
"encoding/json"
"fmt"
"git.icechen.cn/monorepo/backend/pkg/etcd"
"github.com/pkg/errors"
)
const (
prefix = "/config"
env = "/env"
)
const (
EnvTest = "test"
EnvOnl = "onl"
)
// GetConfig 根据etcd获取存入配置
func GetConfig(name string, config interface{}) error {
key := fmt.Sprintf("%v/config/%v", prefix, name)
value, err := etcd.GetValue(key)
if err != nil {
return err
}
err = json.Unmarshal([]byte(value), config)
if err != nil {
return errors.WithMessage(err, "etcd配置解析到json失败")
}
return nil
}
func GetMysql(name string) (string, error) {
key := fmt.Sprintf("%v/mysql/%v", prefix, name)
return etcd.GetValue(key)
}
func GetEnv() (string, error) {
return etcd.GetValue(env)
}
func IsTest() bool {
envString, _ := GetEnv()
return envString == EnvTest
}
func IsOnl() bool {
envString, _ := GetEnv()
return envString == EnvOnl
}
+36
View File
@@ -0,0 +1,36 @@
package config
import (
"fmt"
"testing"
)
type config struct {
Redis string `json:"redis,omitempty"`
Es string `json:"es,omitempty"`
}
func TestGetMysql(t *testing.T) {
//获取 /config/mysql/api-zeus 的str
mysql, err := GetMysql("api-zeus")
if err != nil {
fmt.Println(err)
}
fmt.Println(mysql)
}
func TestConfig(t *testing.T) {
c := new(config)
err := GetConfig("api-zeus", c)
if err != nil {
fmt.Println(err)
}
}
func TestEnv(t *testing.T) {
env, err := GetEnv()
if err != nil {
fmt.Println(err)
}
fmt.Println(env)
}
+12
View File
@@ -0,0 +1,12 @@
package env
import "os"
func GetEnvDefault(key, defVal string) string {
val, ex := os.LookupEnv(key)
if !ex {
os.Setenv(key, defVal)
return defVal
}
return val
}
+53
View File
@@ -0,0 +1,53 @@
package etcd
import (
"context"
"fmt"
"git.icechen.cn/monorepo/backend/pkg/env"
"github.com/pkg/errors"
clientV3 "go.etcd.io/etcd/client/v3"
"strings"
"time"
)
const (
EndPoints = "endpoints"
EndAddress = "etcd:2379"
)
var (
client *clientV3.Client
config clientV3.Config
err error
)
func connect() error {
envDefault := env.GetEnvDefault(EndPoints, EndAddress)
ends := strings.Split(envDefault, ",")
config = clientV3.Config{
Endpoints: ends,
DialTimeout: 5 * time.Second,
}
if client, err = clientV3.New(config); err != nil {
return errors.WithMessage(err, "etcd 连接错误")
}
return nil
}
func GetValue(key string) (string, error) {
if err = connect(); err != nil {
return "", err
}
kv := clientV3.NewKV(client)
defer client.Close()
ctx, cancel := context.WithTimeout(context.TODO(), time.Second*3)
defer cancel()
if getResp, err := kv.Get(ctx, key, clientV3.WithPrefix()); err == nil {
for _, v := range getResp.Kvs {
return string(v.Value), nil
}
} else {
return "", errors.New("etcd 连接超时")
}
return "", errors.New(fmt.Sprintf("没有根据%v找到对应value", key))
}
+1
View File
@@ -0,0 +1 @@
package etcd
+302
View File
@@ -0,0 +1,302 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: user.proto
package lark
import (
context "context"
fmt "fmt"
proto "github.com/golang/protobuf/proto"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
math "math"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
type LoginRequest struct {
Code string `protobuf:"bytes,1,opt,name=code,proto3" json:"code,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *LoginRequest) Reset() { *m = LoginRequest{} }
func (m *LoginRequest) String() string { return proto.CompactTextString(m) }
func (*LoginRequest) ProtoMessage() {}
func (*LoginRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_116e343673f7ffaf, []int{0}
}
func (m *LoginRequest) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_LoginRequest.Unmarshal(m, b)
}
func (m *LoginRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_LoginRequest.Marshal(b, m, deterministic)
}
func (m *LoginRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_LoginRequest.Merge(m, src)
}
func (m *LoginRequest) XXX_Size() int {
return xxx_messageInfo_LoginRequest.Size(m)
}
func (m *LoginRequest) XXX_DiscardUnknown() {
xxx_messageInfo_LoginRequest.DiscardUnknown(m)
}
var xxx_messageInfo_LoginRequest proto.InternalMessageInfo
func (m *LoginRequest) GetCode() string {
if m != nil {
return m.Code
}
return ""
}
type LoginResponse struct {
AccessToken string `protobuf:"bytes,1,opt,name=access_token,json=accessToken,proto3" json:"access_token,omitempty"`
Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"`
EnName string `protobuf:"bytes,3,opt,name=en_name,json=enName,proto3" json:"en_name,omitempty"`
AvatarUrl string `protobuf:"bytes,4,opt,name=avatar_url,json=avatarUrl,proto3" json:"avatar_url,omitempty"`
AvatarThumb string `protobuf:"bytes,5,opt,name=avatar_thumb,json=avatarThumb,proto3" json:"avatar_thumb,omitempty"`
AvatarMiddle string `protobuf:"bytes,6,opt,name=avatar_middle,json=avatarMiddle,proto3" json:"avatar_middle,omitempty"`
AvatarBig string `protobuf:"bytes,7,opt,name=avatar_big,json=avatarBig,proto3" json:"avatar_big,omitempty"`
OpenId string `protobuf:"bytes,8,opt,name=open_id,json=openId,proto3" json:"open_id,omitempty"`
UnionId string `protobuf:"bytes,9,opt,name=union_id,json=unionId,proto3" json:"union_id,omitempty"`
Email string `protobuf:"bytes,10,opt,name=email,proto3" json:"email,omitempty"`
UserId string `protobuf:"bytes,11,opt,name=user_id,json=userId,proto3" json:"user_id,omitempty"`
Mobile string `protobuf:"bytes,12,opt,name=mobile,proto3" json:"mobile,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *LoginResponse) Reset() { *m = LoginResponse{} }
func (m *LoginResponse) String() string { return proto.CompactTextString(m) }
func (*LoginResponse) ProtoMessage() {}
func (*LoginResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_116e343673f7ffaf, []int{1}
}
func (m *LoginResponse) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_LoginResponse.Unmarshal(m, b)
}
func (m *LoginResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_LoginResponse.Marshal(b, m, deterministic)
}
func (m *LoginResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_LoginResponse.Merge(m, src)
}
func (m *LoginResponse) XXX_Size() int {
return xxx_messageInfo_LoginResponse.Size(m)
}
func (m *LoginResponse) XXX_DiscardUnknown() {
xxx_messageInfo_LoginResponse.DiscardUnknown(m)
}
var xxx_messageInfo_LoginResponse proto.InternalMessageInfo
func (m *LoginResponse) GetAccessToken() string {
if m != nil {
return m.AccessToken
}
return ""
}
func (m *LoginResponse) GetName() string {
if m != nil {
return m.Name
}
return ""
}
func (m *LoginResponse) GetEnName() string {
if m != nil {
return m.EnName
}
return ""
}
func (m *LoginResponse) GetAvatarUrl() string {
if m != nil {
return m.AvatarUrl
}
return ""
}
func (m *LoginResponse) GetAvatarThumb() string {
if m != nil {
return m.AvatarThumb
}
return ""
}
func (m *LoginResponse) GetAvatarMiddle() string {
if m != nil {
return m.AvatarMiddle
}
return ""
}
func (m *LoginResponse) GetAvatarBig() string {
if m != nil {
return m.AvatarBig
}
return ""
}
func (m *LoginResponse) GetOpenId() string {
if m != nil {
return m.OpenId
}
return ""
}
func (m *LoginResponse) GetUnionId() string {
if m != nil {
return m.UnionId
}
return ""
}
func (m *LoginResponse) GetEmail() string {
if m != nil {
return m.Email
}
return ""
}
func (m *LoginResponse) GetUserId() string {
if m != nil {
return m.UserId
}
return ""
}
func (m *LoginResponse) GetMobile() string {
if m != nil {
return m.Mobile
}
return ""
}
func init() {
proto.RegisterType((*LoginRequest)(nil), "example_service.LoginRequest")
proto.RegisterType((*LoginResponse)(nil), "example_service.LoginResponse")
}
func init() { proto.RegisterFile("user.proto", fileDescriptor_116e343673f7ffaf) }
var fileDescriptor_116e343673f7ffaf = []byte{
// 320 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x91, 0x41, 0x4b, 0x03, 0x31,
0x10, 0x85, 0x6d, 0xdd, 0x6e, 0xdb, 0x69, 0x8b, 0x10, 0x44, 0xa3, 0x50, 0xd1, 0xf5, 0xe2, 0xa9,
0x07, 0xfd, 0x07, 0x3d, 0x59, 0x50, 0x91, 0xd2, 0x5e, 0xbc, 0x2c, 0xd9, 0xcd, 0x50, 0x43, 0xb3,
0xc9, 0x9a, 0xec, 0x16, 0x7f, 0xae, 0x3f, 0x45, 0x32, 0xd9, 0x43, 0x11, 0xbc, 0xe5, 0x7d, 0xef,
0x65, 0x26, 0xe4, 0x01, 0xb4, 0x1e, 0xdd, 0xa2, 0x76, 0xb6, 0xb1, 0xec, 0x0c, 0xbf, 0x45, 0x55,
0x6b, 0xcc, 0x3d, 0xba, 0x83, 0x2a, 0x31, 0xcb, 0x60, 0xfa, 0x62, 0x77, 0xca, 0xac, 0xf1, 0xab,
0x45, 0xdf, 0x30, 0x06, 0x49, 0x69, 0x25, 0xf2, 0xde, 0x6d, 0xef, 0x61, 0xbc, 0xa6, 0x73, 0xf6,
0xd3, 0x87, 0x59, 0x17, 0xf2, 0xb5, 0x35, 0x1e, 0xd9, 0x1d, 0x4c, 0x45, 0x59, 0xa2, 0xf7, 0x79,
0x63, 0xf7, 0x68, 0xba, 0xf4, 0x24, 0xb2, 0x4d, 0x40, 0x61, 0x90, 0x11, 0x15, 0xf2, 0x7e, 0x1c,
0x14, 0xce, 0xec, 0x12, 0x86, 0x68, 0x72, 0xc2, 0xa7, 0x84, 0x53, 0x34, 0x6f, 0xc1, 0x98, 0x03,
0x88, 0x83, 0x68, 0x84, 0xcb, 0x5b, 0xa7, 0x79, 0x42, 0xde, 0x38, 0x92, 0xad, 0xd3, 0xb4, 0x2e,
0xda, 0xcd, 0x67, 0x5b, 0x15, 0x7c, 0xd0, 0xad, 0x23, 0xb6, 0x09, 0x88, 0xdd, 0xc3, 0xac, 0x8b,
0x54, 0x4a, 0x4a, 0x8d, 0x3c, 0xa5, 0x4c, 0x77, 0xef, 0x95, 0xd8, 0xd1, 0x9a, 0x42, 0xed, 0xf8,
0xf0, 0x78, 0xcd, 0x52, 0xed, 0xc2, 0xf3, 0x6c, 0x8d, 0x26, 0x57, 0x92, 0x8f, 0xe2, 0xf3, 0x82,
0x5c, 0x49, 0x76, 0x05, 0xa3, 0xd6, 0x28, 0x4b, 0xce, 0x98, 0x9c, 0x21, 0xe9, 0x95, 0x64, 0xe7,
0x30, 0xc0, 0x4a, 0x28, 0xcd, 0x81, 0x78, 0x14, 0x61, 0x52, 0xf8, 0xf4, 0x90, 0x9f, 0xc4, 0x49,
0x41, 0xae, 0x24, 0xbb, 0x80, 0xb4, 0xb2, 0x85, 0xd2, 0xc8, 0xa7, 0x91, 0x47, 0xf5, 0xf8, 0x0e,
0xc9, 0xd6, 0xa3, 0x63, 0xcf, 0x30, 0xa0, 0x9f, 0x66, 0xf3, 0xc5, 0x9f, 0xa6, 0x16, 0xc7, 0x35,
0x5d, 0xdf, 0xfc, 0x67, 0xc7, 0x82, 0xb2, 0x93, 0x65, 0xfa, 0x91, 0x68, 0xe1, 0xf6, 0x45, 0x4a,
0xc5, 0x3f, 0xfd, 0x06, 0x00, 0x00, 0xff, 0xff, 0x68, 0x47, 0xbc, 0x3c, 0x06, 0x02, 0x00, 0x00,
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn
// 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.SupportPackageIsVersion4
// UserClient is the client API for User service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type UserClient interface {
Login(ctx context.Context, in *LoginRequest, opts ...grpc.CallOption) (*LoginResponse, error)
}
type userClient struct {
cc *grpc.ClientConn
}
func NewUserClient(cc *grpc.ClientConn) UserClient {
return &userClient{cc}
}
func (c *userClient) Login(ctx context.Context, in *LoginRequest, opts ...grpc.CallOption) (*LoginResponse, error) {
out := new(LoginResponse)
err := c.cc.Invoke(ctx, "/example_service.User/Login", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// UserServer is the server API for User service.
type UserServer interface {
Login(context.Context, *LoginRequest) (*LoginResponse, error)
}
// UnimplementedUserServer can be embedded to have forward compatible implementations.
type UnimplementedUserServer struct {
}
func (*UnimplementedUserServer) Login(ctx context.Context, req *LoginRequest) (*LoginResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method Login not implemented")
}
func RegisterUserServer(s *grpc.Server, srv UserServer) {
s.RegisterService(&_User_serviceDesc, srv)
}
func _User_Login_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(LoginRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(UserServer).Login(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/example_service.User/Login",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(UserServer).Login(ctx, req.(*LoginRequest))
}
return interceptor(ctx, in, info, handler)
}
var _User_serviceDesc = grpc.ServiceDesc{
ServiceName: "example_service.User",
HandlerType: (*UserServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "Login",
Handler: _User_Login_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "user.proto",
}
+29
View File
@@ -0,0 +1,29 @@
syntax = "proto3";
option go_package = "lark";
package example_service;
service User {
rpc Login (LoginRequest) returns (LoginResponse) {}
}
message LoginRequest {
string code = 1;
}
message LoginResponse {
uint64 id = 13;
string access_token = 1;
string name = 2;
string en_name = 3;
string avatar_url = 4;
string avatar_thumb = 5;
string avatar_middle = 6;
string avatar_big = 7;
string open_id = 8;
string union_id = 9;
string email = 10;
string user_id = 11;
string mobile = 12;
}
+45
View File
@@ -0,0 +1,45 @@
package rpc
import (
_ "embed"
"fmt"
"git.icechen.cn/monorepo/backend/pkg/config"
"google.golang.org/grpc"
"os"
"strings"
)
// GetServiceConnByEnv 通过环境变量获取服务的连接
func GetServiceConnByEnv(serviceName string) *grpc.ClientConn {
target := os.Getenv(strings.ToUpper("SERVICE_" + serviceName))
return getConn(target)
}
// GetServiceConn 获取服务的连接
func GetServiceConn(serviceName string) *grpc.ClientConn {
target := "dns:///service-" + serviceName + ":80"
if config.IsTest() {
target = "dns:///service-" + serviceName + "-test:80"
}
return getConn(target)
}
// GetServiceConnWithNamespace 获取跨项目的服务的连接
func GetServiceConnWithNamespace(serviceName string, namespace string) *grpc.ClientConn {
serviceName = serviceName + "." + namespace
target := "dns:///service-" + serviceName + ":80"
if config.IsTest() {
target = "dns:///service-" + serviceName + "-test:80"
}
return getConn(target)
}
func getConn(target string, opts ...grpc.DialOption) *grpc.ClientConn {
opts = append(opts, grpc.WithInsecure())
cli, err := grpc.Dial(target, opts...)
if err != nil {
fmt.Println("target: " + target + " err: " + err.Error())
return nil
}
return cli
}