Compare commits

..

28 Commits

Author SHA1 Message Date
6cd06d86bc add std_owner 2025-04-17 17:18:58 +08:00
zhaoxiaorong
ca9f7047c6 fix 兼容性调整 2025-04-15 21:49:17 +08:00
zhaoxiaorong
2de73fea00 fix 兼容性调整 2025-04-15 20:50:28 +08:00
zhaoxiaorong
4b73f086b1 dev oplog 2025-04-11 18:14:07 +08:00
zhaoxiaorong
c08950c10a fix 2025-04-11 18:06:08 +08:00
zhaoxiaorong
d691648916 fix 2025-04-11 17:53:50 +08:00
zhaoxiaorong
8060cdb508 fix 2025-04-11 17:50:06 +08:00
zhaoxiaorong
50c23df124 fix 2025-04-11 17:44:49 +08:00
zhaoxiaorong
04b8e5b03b fix 2025-04-11 16:45:11 +08:00
zhaoxiaorong
dd95b8d8b1 fix 2025-04-09 15:24:28 +08:00
zhaoxiaorong
dd9a692858 fix 2025-04-09 11:12:42 +08:00
zhaoxiaorong
b5374b85ff fix 2025-04-09 10:56:49 +08:00
zhaoxiaorong
5172824358 fix 2025-04-09 10:34:01 +08:00
zhaoxiaorong
51ff7d1ffd fix 2025-04-09 10:19:15 +08:00
zhaoxiaorong
c7f24e3b6d fix 2025-04-09 09:39:51 +08:00
f7948263c5 Merge branch 'main' of https://git.apinb.com/bsm-sdk/core 2025-04-08 15:20:34 +08:00
fc42bc92ff fix parse meta ctx 2025-04-08 15:20:22 +08:00
b8f693ef82 fix net getLocationIP 2025-04-07 11:14:07 +08:00
6ec06c2813 add third 2025-04-06 13:42:44 +08:00
7983651fcd add time <=> string 2025-04-02 14:53:45 +08:00
d7fb72b5e0 add types.db identity default:uuid_generate_v4() 2025-04-01 23:34:24 +08:00
6d1f59fd35 add gateway 2025-03-30 13:24:13 +08:00
93daa022bc add gateway 2025-03-30 13:23:46 +08:00
ca00b34e24 add GatewayConf 2025-03-29 20:14:26 +08:00
922cfd6a02 feat:service mod 2025-03-29 15:02:49 +08:00
d131495f4f up go.mod 2025-03-27 03:17:48 +08:00
04451d4b2f add conf.PrintInfo 2025-03-27 03:10:56 +08:00
e184fff689 add conf.PrintInfo 2025-03-27 03:08:59 +08:00
17 changed files with 623 additions and 49 deletions

View File

@@ -12,6 +12,7 @@ import (
"git.apinb.com/bsm-sdk/core/env"
"git.apinb.com/bsm-sdk/core/print"
"git.apinb.com/bsm-sdk/core/utils"
"git.apinb.com/bsm-sdk/core/vars"
yaml "gopkg.in/yaml.v3"
)
@@ -28,7 +29,9 @@ func New(srvKey string, cfg any) {
// 构造配置文件路径,输出配置文件信息
cfp := fmt.Sprintf("%s_%s.yaml", strings.ToLower(srvKey), env.Runtime.Mode)
cfp = filepath.Join(env.Runtime.Prefix, "etc", cfp)
print.Info("[BSM - %s] Config File: %s", srvKey, cfp)
print.Info("[BSM - %s] Check Configure ...", vars.ServiceKey)
// 读取配置文件内容
yamlFile, err := os.ReadFile(cfp)
@@ -56,10 +59,24 @@ func NotNil(values ...string) {
}
}
func CheckPort(port int) int {
if port <= 0 || port >= 65535 {
func PrintInfo(addr string) {
print.Success("[BSM - %s] Config Check Success.", vars.ServiceKey)
print.Info("[BSM - %s] Service Name: %s", vars.ServiceKey, vars.ServiceKey)
print.Info("[BSM - %s] Runtime Mode: %s", vars.ServiceKey, env.Runtime.Mode)
}
func CheckPort(port string) string {
if port == "" {
r := rand.New(rand.NewPCG(1000, uint64(time.Now().UnixNano())))
return r.IntN(65535-1024) + 1024 // 生成1024到65535之间的随机端口
p := r.IntN(65535-1024) + 1024 // 生成1024到65535之间的随机端口
return utils.Int2String(p)
}
return port
}
func CheckIP(ip string) string {
if ip == "" {
return utils.GetLocationIP()
}
return ip
}

View File

@@ -1,11 +1,14 @@
package conf
type Base struct {
Service string `yaml:"Service"` // 服务名称
Port int `yaml:"Port"` // 服务监听端口,0为自动随机端口
Cache string `yaml:"Cache"` // REDIS缓存
OnMicroService bool `yaml:"OnMicroService"` // 是否启用微服务
SecretKey string `yaml:"SecretKey"` // 服务秘钥
Service string `yaml:"Service"` // 服务名称
Port string `yaml:"Port"` // 服务监听端口,0为自动随机端口
Cache string `yaml:"Cache"` // REDIS缓存
SecretKey string `yaml:"SecretKey"` // 服务秘钥
BindIP string `yaml:"BindIP"` // 绑定IP
Addr string `yaml:"Addr"`
OnMicroService bool `yaml:"OnMicroService"`
LoginUrl string `yaml:"LoginUrl"`
}
type DBConf struct {
@@ -13,6 +16,16 @@ type DBConf struct {
Source []string `yaml:"Source"` // 数据库连接
}
type MicroServiceConf struct {
Enable bool `yaml:"Enable"` // 是否启用微服务
Anonymous []string `yaml:"Anonymous"`
}
type GatewayConf struct {
Enable bool `yaml:"Enable"` // 是否启用网关服务
Port int `yaml:"Port"` // 服务监听端口
}
type ApmConf struct {
Name string // APM服务名称
Platform string `yaml:"Platform"` // APM平台apm,skywalking
@@ -37,11 +50,14 @@ type RpcConf struct {
}
type OssConf struct {
Platform string `yaml:"Platform"` // oss平台aliyun,tencent,huawei,aws,minio
Site string `yaml:"Site"` // oss站点HOST
Endpoint string `yaml:"Endpoint"` // oss服务接入地址
Region string `yaml:"Region"` // oss服务区域
AccessKeyID string `yaml:"AccessKeyId"` // oss AccessKeyId
AccessKeySecret string `yaml:"AccessKeySecret"` // oss AccessKeySecret
UseSSL bool `yaml:"UseSSL"` // 是否使用SSL
}
type MqConf struct {

9
go.mod
View File

@@ -6,6 +6,7 @@ require (
github.com/FishGoddess/cachego v0.6.1
github.com/elastic/go-elasticsearch/v8 v8.17.1
github.com/google/uuid v1.6.0
github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3
github.com/nats-io/nats.go v1.39.0
github.com/oklog/ulid/v2 v2.1.0
github.com/redis/go-redis/v9 v9.7.0
@@ -17,8 +18,8 @@ require (
)
require (
github.com/bytedance/sonic v1.12.8 // indirect
github.com/bytedance/sonic/loader v0.2.3 // indirect
github.com/bytedance/sonic v1.13.2 // indirect
github.com/bytedance/sonic/loader v0.2.4 // indirect
github.com/cloudwego/base64x v0.1.5 // indirect
github.com/gabriel-vasile/mimetype v1.4.8 // indirect
github.com/gin-contrib/sse v1.0.0 // indirect
@@ -75,8 +76,8 @@ require (
golang.org/x/sync v0.11.0 // indirect
golang.org/x/sys v0.30.0 // indirect
golang.org/x/text v0.22.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20250212204824-5a70512c5d8b // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20250212204824-5a70512c5d8b // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20250303144028-a0af3efb3deb // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20250303144028-a0af3efb3deb // indirect
google.golang.org/grpc v1.70.0
google.golang.org/protobuf v1.36.5 // indirect
)

22
go.sum
View File

@@ -4,11 +4,11 @@ github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
github.com/bytedance/sonic v1.12.8 h1:4xYRVRlXIgvSZ4e8iVTlMF5szgpXd4AfvuWgA8I8lgs=
github.com/bytedance/sonic v1.12.8/go.mod h1:uVvFidNmlt9+wa31S1urfwwthTWteBgG0hWuoKAXTx8=
github.com/bytedance/sonic v1.13.2 h1:8/H1FempDZqC4VqjptGo14QQlJx8VdZJegxs6wwfqpQ=
github.com/bytedance/sonic v1.13.2/go.mod h1:o68xyaF9u2gvVBuGHPlUVCy+ZfmNNO5ETf1+KgkJhz4=
github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
github.com/bytedance/sonic/loader v0.2.3 h1:yctD0Q3v2NOGfSWPLPvG2ggA2kV6TS6s4wioyEqssH0=
github.com/bytedance/sonic/loader v0.2.3/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI=
github.com/bytedance/sonic/loader v0.2.4 h1:ZWCw4stuXUsn1/+zQDqeE7JKP+QO47tz7QCNan80NzY=
github.com/bytedance/sonic/loader v0.2.4/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/cloudwego/base64x v0.1.5 h1:XPciSp1xaq2VCSt6lF0phncD4koWyULpl5bUxbfCyP4=
@@ -56,11 +56,13 @@ github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3 h1:5ZPtiqj0JL5oKWmcsq4VMaAW5ukBEgSGXEN89zeH1Jo=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3/go.mod h1:ndYquD05frm2vACXE1nsccT4oJzjhw2arTS2cpUD1PI=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
@@ -203,10 +205,10 @@ golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8T
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/genproto/googleapis/api v0.0.0-20250212204824-5a70512c5d8b h1:i+d0RZa8Hs2L/MuaOQYI+krthcxdEbEM2N+Tf3kJ4zk=
google.golang.org/genproto/googleapis/api v0.0.0-20250212204824-5a70512c5d8b/go.mod h1:iYONQfRdizDB8JJBybql13nArx91jcUk7zCXEsOofM4=
google.golang.org/genproto/googleapis/rpc v0.0.0-20250212204824-5a70512c5d8b h1:FQtJ1MxbXoIIrZHZ33M+w5+dAP9o86rgpjoKr/ZmT7k=
google.golang.org/genproto/googleapis/rpc v0.0.0-20250212204824-5a70512c5d8b/go.mod h1:8BS3B93F/U1juMFq9+EDk+qOT5CO1R9IzXxG3PTqiRk=
google.golang.org/genproto/googleapis/api v0.0.0-20250303144028-a0af3efb3deb h1:p31xT4yrYrSM/G4Sn2+TNUkVhFCbG9y8itM2S6Th950=
google.golang.org/genproto/googleapis/api v0.0.0-20250303144028-a0af3efb3deb/go.mod h1:jbe3Bkdp+Dh2IrslsFCklNhweNTBgSYanP1UXhJDhKg=
google.golang.org/genproto/googleapis/rpc v0.0.0-20250303144028-a0af3efb3deb h1:TLPQVbx1GJ8VKZxz52VAxl1EBgKXXbTiU9Fc5fZeLn4=
google.golang.org/genproto/googleapis/rpc v0.0.0-20250303144028-a0af3efb3deb/go.mod h1:LuRYeWDFV6WOn90g357N17oMCaxpgCnbi/44qJvDn2I=
google.golang.org/grpc v1.70.0 h1:pWFv03aZoHzlRKHWicjsZytKAiYCtNS0dHbXnIdq7jQ=
google.golang.org/grpc v1.70.0/go.mod h1:ofIJqVKDXx/JiXrwr2IG4/zwdH9txy3IlF40RmcJSQw=
google.golang.org/protobuf v1.36.5 h1:tPhr+woSbjfYvY6/GPufUoYizxw1cF/yFoxJ2fmpwlM=

View File

@@ -17,14 +17,14 @@ var (
type service struct{}
func (s *service) Register(cli *clientv3.Client, serviceName string, port int) error {
func (s *service) Register(cli *clientv3.Client, serviceName string, port string) error {
lease := clientv3.NewLease(cli)
grantResp, err := lease.Grant(context.TODO(), 5)
if err != nil {
return err
}
serviceAddr := utils.GetLocationIP() + ":" + utils.Int2String(port)
serviceAddr := utils.GetLocationIP() + ":" + port
key := RootPrefix + serviceName + "/" + utils.Int642String(time.Now().UnixNano())
_, err = cli.KV.Put(context.TODO(), key, serviceAddr, clientv3.WithLease(grantResp.ID))

73
middleware/jwt.go Normal file
View File

@@ -0,0 +1,73 @@
package middleware
import (
"encoding/json"
"fmt"
"log"
"net/http"
"git.apinb.com/bsm-sdk/core/cache/redis"
"git.apinb.com/bsm-sdk/core/crypto/encipher"
"git.apinb.com/bsm-sdk/core/errcode"
"git.apinb.com/bsm-sdk/core/types"
"github.com/gin-gonic/gin"
)
func JwtAuth(redis *redis.RedisClient) gin.HandlerFunc {
return func(c *gin.Context) {
// 从请求头中获取 Authorization
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
log.Println("获取token异常:", "Authorization header is required")
c.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization header is required"})
c.Abort()
return
}
// 提取Token
claims, err := encipher.ParseTokenAes(authHeader)
if err != nil || claims == nil {
log.Println("提取token异常:", "Token is required")
c.JSON(http.StatusUnauthorized, gin.H{"error": "Token is required"})
c.Abort()
return
}
// 从redis 获取token,判断当前redis 是否为空
tokenKey := fmt.Sprintf("%d-%s-%s", claims.ID, claims.Role, "token")
redisToken := redis.Client.Get(redis.Ctx, tokenKey)
if redisToken.Val() == "" {
log.Println("redis异常", "Token status unauthorized")
c.JSON(http.StatusUnauthorized, gin.H{"error": "Token status unauthorized"})
c.Abort()
return
}
// 将解析后的 Token 存储到上下文中
c.Set("Auth", claims)
// 如果 Token 有效,继续处理请求
c.Next()
}
}
// 获取上下文用户登录信息
func ParseAuth(c *gin.Context) (*types.JwtClaims, error) {
claims, ok := c.Get("Auth")
if !ok {
log.Printf("获取登录信息异常: %v", errcode.ErrJWTAuthNotFound)
return nil, errcode.ErrJWTAuthNotFound
}
json_claims, err := json.Marshal(claims)
if err != nil {
log.Printf("解析json异常: %v", err)
return nil, errcode.ErrJsonMarshal
}
var auth *types.JwtClaims
if err := json.Unmarshal(json_claims, &auth); err != nil {
log.Printf("解析json异常: %v", err)
return nil, errcode.ErrJsonUnmarshal
}
return auth, nil
}

14
oplog/new.go Normal file
View File

@@ -0,0 +1,14 @@
package oplog
import (
"encoding/json"
"git.apinb.com/bsm-sdk/core/utils"
)
func New(endpoint string, data []*LogItem) {
jsonBytes, _ := json.Marshal(data)
go utils.HttpPost(endpoint, nil, jsonBytes)
}

18
oplog/types.go Normal file
View File

@@ -0,0 +1,18 @@
package oplog
type LogItem struct {
OpID uint `json:"op_id"`
OpName string `json:"op_name"`
OpType string `json:"op_type"`
Text string `json:"text"`
}
var (
Type_Login string = "login"
Type_Logout string = "logout"
Type_Register string = "register"
Type_Update string = "update"
Type_Delete string = "delete"
Type_Query string = "query"
Type_Other string = "other"
)

View File

@@ -15,24 +15,24 @@ func init() {
// record INFO message. Color White
func Info(format string, a ...interface{}) {
message := fmt.Sprintf("\033[37m[Info] "+format+"\033[0m\n", a...)
message := fmt.Sprintf("\033[37m[Info] "+format+"\033[0m\n", a...)
logger.Print(message)
}
// record Warn message. Color Orange
func Warn(format string, a ...interface{}) {
message := fmt.Sprintf("\033[33m[Warn] "+format+"\033[0m\n", a...)
message := fmt.Sprintf("\033[33m[Warn] "+format+"\033[0m\n", a...)
logger.Print(message)
}
// record Success message. Color Green
func Success(format string, a ...interface{}) {
message := fmt.Sprintf("\033[32m[Success] "+format+"\033[0m\n", a...)
message := fmt.Sprintf("\033[32m[Succ] "+format+"\033[0m\n", a...)
logger.Print(message)
}
// record ERROR message. Color Red
func Error(format string, a ...interface{}) {
message := fmt.Sprintf("\033[31m[Error] "+format+"\033[0m\n", a...)
message := fmt.Sprintf("\033[31m[Error] "+format+"\033[0m\n", a...)
logger.Print(message)
}

60
service/meta.go Normal file
View File

@@ -0,0 +1,60 @@
package service
import (
"context"
"git.apinb.com/bsm-sdk/core/crypto/encipher"
"git.apinb.com/bsm-sdk/core/errcode"
"git.apinb.com/bsm-sdk/core/types"
"git.apinb.com/bsm-sdk/core/utils"
"google.golang.org/grpc/metadata"
)
// 解析Context中MetaData的数据
type ParseOptions struct {
RoleValue string // 判断角色的值
MustPrivateAllow bool // 是否只允许私有IP访问
}
func ParseMetaCtx(ctx context.Context, opts *ParseOptions) (*types.JwtClaims, error) {
// 解析metada中的信息并验证
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, errcode.ErrJWTAuthNotFound
}
var Authorizations []string = md.Get("authorization")
if len(Authorizations) == 0 || Authorizations[0] == "" {
return nil, errcode.ErrJWTAuthNotFound
}
claims, err := encipher.ParseTokenAes(Authorizations[0])
if err != nil {
return nil, err
}
if opts != nil {
if !checkRole(claims, "role", opts.RoleValue) {
return nil, errcode.ErrPermissionDenied
}
if opts.MustPrivateAllow {
if utils.IsPublicIP(claims.Client) {
return nil, errcode.ErrPermissionDenied
}
}
}
return claims, nil
}
func checkRole(claims *types.JwtClaims, roleKey, roleValue string) bool {
if roleValue == "" {
return true
}
if role, exists := claims.Extend[roleKey]; !exists || role != roleValue {
return false
} else {
return true
}
}

128
service/register.go Normal file
View File

@@ -0,0 +1,128 @@
package service
import (
"context"
"strings"
"time"
"git.apinb.com/bsm-sdk/core/print"
"git.apinb.com/bsm-sdk/core/vars"
clientv3 "go.etcd.io/etcd/client/v3"
)
// ServiceRegister 创建租约注册服务
type ServiceRegister struct {
cli *clientv3.Client //etcd client
leaseID clientv3.LeaseID //租约ID
//租约keepalieve相应chan
keepAliveChan <-chan *clientv3.LeaseKeepAliveResponse
key string //key
val string //value
}
// NewRegister 注册服务至路由表.
//
// ec:EtcdConfig;
//
// routeKey: ServiceRouteRootPrefix + ServiceKey + "/" + utils.GetLocationIP() + addr;
//
// gs:grpc.Server;
func RegisterService(cli *clientv3.Client, routeKey string, methods []string, lease int64) (*ServiceRegister, error) {
ser := &ServiceRegister{
cli: cli,
key: routeKey,
val: strings.Join(methods, ","),
}
//申请租约设置时间keepalive
if err := ser.putKeyWithLease(lease); err != nil {
return nil, err
}
return ser, nil
}
// 设置租约
func (s *ServiceRegister) putKeyWithLease(lease int64) error {
//设置租约时间
resp, err := s.cli.Grant(context.Background(), lease)
if err != nil {
return err
}
//注册服务并绑定租约
_, err = s.cli.Put(context.Background(), s.key, s.val, clientv3.WithLease(resp.ID))
if err != nil {
return err
}
//设置续租 定期发送需求请求
leaseRespChan, err := s.cli.KeepAlive(context.Background(), resp.ID)
if err != nil {
return err
}
s.leaseID = resp.ID
s.keepAliveChan = leaseRespChan
return nil
}
// ListenLeaseRespChan 监听 续租情况
func (s *ServiceRegister) ListenLeaseRespChan() {
for {
select {
case leaseKeepResp := <-s.keepAliveChan:
if leaseKeepResp == nil {
//log.Println("close lease.")
return
} else {
goto END
}
}
END:
time.Sleep(500 * time.Millisecond)
}
}
// Close 注销服务
func (s *ServiceRegister) Close() error {
//撤销租约
if _, err := s.cli.Revoke(context.Background(), s.leaseID); err != nil {
return err
}
return s.cli.Close()
}
func (s *ServiceRegister) SetAnonymous(key string, urls []string) {
// remove reppeat, clear service all anonymous uri.
anonymous, _ := s.cli.Get(context.Background(), key)
var as []string
if len(anonymous.Kvs) > 0 {
val := string(anonymous.Kvs[0].Value)
as = strings.Split(val, ",")
}
as = append(clearService(as), urls...)
newAnonymous := strings.Join(as, ",")
// put anonymous to etcd
_, err := s.cli.Put(context.Background(), key, newAnonymous)
if err != nil {
print.Error("[BSM Register] Anonymous Fail.")
} else {
print.Info("[BSM Register] Anonymous: %s", newAnonymous)
}
}
func clearService(as []string) (out []string) {
for _, v := range as {
if len(v) >= len(vars.ServiceKey) {
if v[0:len(vars.ServiceKey)] != vars.ServiceKey {
out = append(out, v)
}
}
}
return
}

125
service/service.go Normal file
View File

@@ -0,0 +1,125 @@
package service
import (
"context"
"log"
"net"
"os"
"strconv"
"strings"
"net/http"
gwRuntime "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"git.apinb.com/bsm-sdk/core/conf"
"git.apinb.com/bsm-sdk/core/env"
"git.apinb.com/bsm-sdk/core/print"
"git.apinb.com/bsm-sdk/core/vars"
clientv3 "go.etcd.io/etcd/client/v3"
"google.golang.org/grpc"
)
type (
// RegisterFn defines the method to register a server.
RegisterFn func(*grpc.Server)
Service struct {
GrpcSrv *grpc.Server
Opts *Options
}
Options struct {
Addr string
EtcdClient *clientv3.Client
MsConf *conf.MicroServiceConf
GatewayConf *conf.GatewayConf
GatewayCtx context.Context
GatewayMux *gwRuntime.ServeMux
}
)
func New(srv *grpc.Server, opts *Options) *Service {
return &Service{GrpcSrv: srv, Opts: opts}
}
func Addr(ip string, port int) string {
return net.JoinHostPort(ip, strconv.Itoa(port))
}
func (s *Service) Start() {
print.Info("[BSM - %s] Service Starting ...", vars.ServiceKey)
// register to etcd.
if s.Opts.MsConf != nil && s.Opts.MsConf.Enable {
if s.Opts.EtcdClient == nil {
print.Error("[BSM Register] Etcd Client is nil.")
os.Exit(1)
}
print.Info("[BSM - %s] Registering Service to Etcd ...", vars.ServiceKey)
// get methods
methods := FoundGrpcMethods(s.GrpcSrv)
// set router key
routerKey := vars.ServiceRootPrefix + "Router/" + env.Runtime.Workspace + "/" + strings.ToLower(vars.ServiceKey) + "/" + s.Opts.Addr
// register to etcd
register, err := RegisterService(s.Opts.EtcdClient, routerKey, methods, vars.ServiceLease)
if err != nil {
log.Panicf("[ERROR] %s Service Register:%s \n", vars.ServiceKey, err.Error())
}
anonKey := vars.ServiceRootPrefix + "Router/" + env.Runtime.Workspace + "/"
register.SetAnonymous(anonKey, s.Opts.MsConf.Anonymous)
// service register lease
go register.ListenLeaseRespChan()
}
// run grpc srv.
tcpListen, err := net.Listen("tcp", s.Opts.Addr)
if err != nil {
panic(err)
}
go func() {
if err := s.GrpcSrv.Serve(tcpListen); err != nil {
panic(err)
}
}()
print.Success("[BSM - %s] Grpc %s Runing Success !", vars.ServiceKey, s.Opts.Addr)
if s.Opts.GatewayConf != nil && s.Opts.GatewayConf.Enable {
addr := Addr("0.0.0.0", s.Opts.GatewayConf.Port)
go s.Gateway(s.Opts.Addr, addr)
print.Success("[BSM - %s] Http %s Runing Success!", vars.ServiceKey, addr)
}
select {}
}
func (s *Service) Gateway(grpcAddr string, httpAddr string) {
// 1. 定义一个context
_, cancel := context.WithCancel(s.Opts.GatewayCtx)
defer cancel()
http.ListenAndServe(httpAddr, s.Opts.GatewayMux)
}
func (s *Service) Stop() {
s.GrpcSrv.GracefulStop()
}
// found grpc methods.
func FoundGrpcMethods(s *grpc.Server) []string {
var mothods []string
for key, srv := range s.GetServiceInfo() {
srvName := strings.Split(key, ".")[1]
for _, mn := range srv.Methods {
mothods = append(mothods, srvName+"."+mn.Name)
}
}
return mothods
}

65
third/wechat.go Normal file
View File

@@ -0,0 +1,65 @@
package third
import (
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"errors"
)
func WeChat_Decrypt(sessionKey, encryptedData, iv string) (string, error) {
aesKey, err := base64.StdEncoding.DecodeString(sessionKey)
if err != nil {
return "", err
}
cipherText, err := base64.StdEncoding.DecodeString(encryptedData)
if err != nil {
return "", err
}
ivBytes, err := base64.StdEncoding.DecodeString(iv)
if err != nil {
return "", err
}
block, err := aes.NewCipher(aesKey)
if err != nil {
return "", err
}
mode := cipher.NewCBCDecrypter(block, ivBytes)
mode.CryptBlocks(cipherText, cipherText)
cipherText, err = WeChat_Pkcs7Unpad(cipherText, block.BlockSize())
if err != nil {
return "", err
}
return string(cipherText), nil
}
// pkcs7Unpad returns slice of the original data without padding
func WeChat_Pkcs7Unpad(data []byte, blockSize int) ([]byte, error) {
var (
// ErrInvalidBlockSize block size不合法
ErrInvalidBlockSize = errors.New("invalid block size")
// ErrInvalidPKCS7Data PKCS7数据不合法
ErrInvalidPKCS7Data = errors.New("invalid PKCS7 data")
// ErrInvalidPKCS7Padding 输入padding失败
ErrInvalidPKCS7Padding = errors.New("invalid padding on input")
)
if blockSize <= 0 {
return nil, ErrInvalidBlockSize
}
if len(data)%blockSize != 0 || len(data) == 0 {
return nil, ErrInvalidPKCS7Data
}
c := data[len(data)-1]
n := int(c)
if n == 0 || n > len(data) {
return nil, ErrInvalidPKCS7Padding
}
for i := 0; i < n; i++ {
if data[len(data)-n+i] != c {
return nil, ErrInvalidPKCS7Padding
}
}
return data[:len(data)-n], nil
}

View File

@@ -28,30 +28,36 @@ type (
Std_IICUDS struct {
ID uint `gorm:"primarykey;" json:"id"`
Identity string `gorm:"column:identity;type:varchar(36);uniqueIndex;" json:"identity"` // 唯一标识24位NanoID,36位为ULID
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
CreatedAt time.Time `gorm:"" json:"created_at"`
UpdatedAt time.Time `gorm:"" json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index;" json:"deleted_at"`
Status int64 `gorm:"default:0;index;" json:"status"` // 状态默认为0-1禁止1为正常
Status int8 `gorm:"default:0;index;" json:"status"` // 状态默认为0-1禁止1为正常
}
// standard ID,Identity,Created,Updated,Deleted,Status definition.
Std_ICUD struct {
ID uint `gorm:"primarykey;" json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
CreatedAt time.Time `gorm:"" json:"created_at"`
UpdatedAt time.Time `gorm:"" json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index;" json:"deleted_at"`
}
// standard ID,Created definition.
Std_IdCreated struct {
ID uint `gorm:"primarykey;" json:"id"`
CreatedAt time.Time `json:"created_at"`
CreatedAt time.Time `gorm:"" json:"created_at"`
}
// standard PassportID,PassportIdentity definition.
Std_Passport struct {
PassportID uint `gorm:"column:passport_id;Index;" json:"passport_id"`
PassportIdentity string `gorm:"column:passport_identity;type:varchar(36);Index;" json:"passport_identity"` // 用户唯一标识24位NanoID,36位为ULID
PassportIdentity string `gorm:"column:passport_identity;type:varchar(36);Index;" json:"passport_identity"` // 用户唯一标识24位NanoID,36位为UUID
}
// standard OwnerID,OwnerIdentity definition.
Std_Owner struct {
OwnerID uint `gorm:"column:owner_id;Index;" json:"owner_id"`
OwnerIdentity string `gorm:"column:owner_identity;type:varchar(36);Index;" json:"owner_identity"` // 用户唯一标识24位NanoID,36位为UUID
}
// standard ID definition.
@@ -61,7 +67,7 @@ type (
// standard Identity definition.
Std_Identity struct {
Identity string `gorm:"column:identity;type:varchar(36);uniqueIndex;" json:"identity"` // 唯一标识24位NanoID,36位为ULID
Identity string `gorm:"column:identity;type:varchar(36);uniqueIndex;" json:"identity"` // 唯一标识24位NanoID,36位为UUID
}
// standard Status definition.

View File

@@ -9,6 +9,7 @@ import (
"net/http"
"os"
"strconv"
"strings"
)
func IsPublicIP(ipString string) bool {
@@ -32,24 +33,55 @@ func IsPublicIP(ipString string) bool {
}
// Get Location IP .
func GetLocationIP() string {
addrs, err := net.InterfaceAddrs()
func GetLocationIP() (localIp string) {
localIp = "127.0.0.1"
// Get all network interfaces
interfaces, err := net.Interfaces()
if err != nil {
return ""
return
}
ip := ""
for _, a := range addrs {
if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
ip = ipnet.IP.String()
break
for _, iface := range interfaces {
// Skip the loopback interface
if iface.Flags&net.FlagLoopback != 0 {
continue
}
// Get addresses associated with the interface
addrs, err := iface.Addrs()
if err != nil {
continue
}
for _, addr := range addrs {
// Check if the address is an IPNet
ipnet, ok := addr.(*net.IPNet)
if !ok || ipnet.IP.IsLoopback() {
continue
}
// Get the IP address
ip := ipnet.IP.To4()
if ip == nil {
continue
}
// Skip IP addresses in the 169.254.x.x range
if strings.HasPrefix(ip.String(), "169.254") {
continue
}
// Skip IP addresses in the 169.254.x.x range
if strings.HasPrefix(ip.String(), "26.26") {
continue
}
// Return the first valid IP address found
return ip.String()
}
}
if ip == "" {
return ""
}
return ip
return
}
func LocalIPv4s() ([]string, error) {

14
utils/time.go Normal file
View File

@@ -0,0 +1,14 @@
package utils
import (
"time"
)
func Time2String(layout string, t time.Time) string {
return t.Format(layout)
}
func String2Time(layout, in string) time.Time {
t, _ := time.ParseInLocation(layout, in, time.Local)
return t
}

View File

@@ -4,4 +4,7 @@ var (
RUN_MODE_DEV = "dev"
RUN_MODE_TEST = "test"
RUN_MODE_PROD = "prod"
ServiceLease int64 = 60
ServiceRootPrefix string = "/"
)