Compare commits
40 Commits
Author | SHA1 | Date |
---|---|---|
yanweidong | fe3e02370c | |
yanweidong | 3dfadd7a30 | |
yanweidong | 175848c47e | |
yanweidong | 839d85d493 | |
yanweidong | 3b5719bc91 | |
yanweidong | ec2bf11981 | |
yanweidong | 9bb2a1d730 | |
yanweidong | d645a49c97 | |
yanweidong | a8efe29c7f | |
yanweidong | 3d609bfba8 | |
yanweidong | 8537320513 | |
david | 0be9490840 | |
david | 84d6a9d034 | |
david | 59118cf8f2 | |
yanweidong | aada90ea78 | |
yanweidong | 28ad46d403 | |
david | 31c602dcc5 | |
david | 52e78a321e | |
yanweidong | 6cac60f15e | |
yanweidong | 2d40fc38ce | |
yanweidong | f83797a746 | |
zhaoxiaorong | c255ffb558 | |
phpstudyer | 4003529b5c | |
yanweidong | 25ecea7e09 | |
yanweidong | 76fd17c0f0 | |
yanweidong | 07626c9d54 | |
yanweidong | ddc1eb90d8 | |
yanweidong | 2ef1de8118 | |
david | 29fb426c60 | |
david | f2f179d984 | |
yanweidong | 26048b1b41 | |
yanweidong | 8bff8e7377 | |
yanweidong | 983545b0d7 | |
david | 7575423cff | |
david | acaaa8d6ed | |
david | a357fa225b | |
yanweidong | 31a80eb904 | |
yanweidong | 87ea785119 | |
yanweidong | 79363aabf0 | |
david | 04537f27f0 |
|
@ -19,6 +19,8 @@ func parseArgs(cmd string) {
|
|||
switch cmd {
|
||||
case "-v", "--v", "-version", "--version":
|
||||
versionCmd()
|
||||
case "--json":
|
||||
versionCmdJson()
|
||||
}
|
||||
|
||||
os.Exit(0)
|
||||
|
@ -28,3 +30,7 @@ func versionCmd() {
|
|||
fmt.Printf("[Blocks Service: %s] Version: %s \n", vars.ServiceKey, vars.VERSION)
|
||||
fmt.Printf("[Blocks Service: %s] Compile: %s by %s build.\n", vars.ServiceKey, vars.GO_VERSION, vars.BUILD_TIME)
|
||||
}
|
||||
|
||||
func versionCmdJson() {
|
||||
fmt.Printf("{\"version\":\"%s\",\"build_time\":\"%s\"}\n", vars.VERSION, vars.BUILD_TIME)
|
||||
}
|
||||
|
|
|
@ -0,0 +1,30 @@
|
|||
package sql
|
||||
|
||||
import "strings"
|
||||
|
||||
// key,value To like sql
|
||||
func Like(key, val string) string {
|
||||
if val == "" {
|
||||
return ""
|
||||
}
|
||||
key = strings.TrimSpace(key)
|
||||
val = strings.TrimSpace(val)
|
||||
return key + " LIKE '%" + val + "%'"
|
||||
}
|
||||
|
||||
// map strings to like sqls
|
||||
func Likes(in map[string]string) string {
|
||||
var ar []string
|
||||
for key, val := range in {
|
||||
sql := Like(key, val)
|
||||
if sql != "" {
|
||||
ar = append(ar, sql)
|
||||
}
|
||||
}
|
||||
|
||||
if len(ar) == 0 {
|
||||
return ""
|
||||
}
|
||||
|
||||
return strings.Join(ar, " AND ")
|
||||
}
|
|
@ -24,14 +24,15 @@ func NewPostgreSql(dsn string, options *types.SqlOptions) (*gorm.DB, error) {
|
|||
}
|
||||
|
||||
//控制台和文件同时输出日志
|
||||
var newLogger = setLogger(vars.ServiceKey, options.LogStdout)
|
||||
//var newLogger = setLogger(vars.ServiceKey, options.LogStdout)
|
||||
|
||||
gormDb, err := gorm.Open(postgres.New(postgres.Config{
|
||||
DSN: dsn,
|
||||
// PreferSimpleProtocol: true, disables implicit prepared statement usage
|
||||
|
||||
}), &gorm.Config{
|
||||
Logger: newLogger,
|
||||
//Logger:newLogger,
|
||||
DisableForeignKeyConstraintWhenMigrating: true,
|
||||
NamingStrategy: schema.NamingStrategy{
|
||||
SingularTable: true, // 使用单数表名,启用该选项,此时,`User` 的表名应该是 `t_user`
|
||||
}})
|
||||
|
|
|
@ -6,7 +6,6 @@ import (
|
|||
"crypto/cipher"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
|
@ -22,25 +21,29 @@ var (
|
|||
JwtSecretLen int
|
||||
)
|
||||
|
||||
func New() {
|
||||
JwtSecret = []byte(env.MeshEnv.JwtSecretKey)
|
||||
func New(token string) {
|
||||
JwtSecret = []byte(token)
|
||||
JwtSecretLen = len(env.MeshEnv.JwtSecretKey)
|
||||
}
|
||||
|
||||
func GenerateTokenAes(id uint, identity, client, role string, extend map[string]string) (string, error) {
|
||||
func GenerateTokenAes(id uint, identity, client, role string, owner any, extend map[string]string) (string, error) {
|
||||
if (JwtSecretLen == 16 || JwtSecretLen == 24 || JwtSecretLen == 32) == false {
|
||||
return "", exception.ErrAuthSecret
|
||||
}
|
||||
expireTime := time.Now().Add(vars.JwtExpireDay)
|
||||
claims := types.JwtClaims{
|
||||
ID: id,
|
||||
Identity: identity,
|
||||
Extend: extend,
|
||||
Client: client,
|
||||
Extend: extend,
|
||||
Owner: owner,
|
||||
Role: role,
|
||||
ExpiresAt: expireTime.Unix(),
|
||||
}
|
||||
|
||||
byte, err := json.Marshal(claims)
|
||||
if err != nil {
|
||||
return "", err
|
||||
return "", exception.ErrJsonEncode
|
||||
}
|
||||
|
||||
token, err := AesEncryptCBC(byte)
|
||||
|
@ -51,12 +54,13 @@ func GenerateTokenAes(id uint, identity, client, role string, extend map[string]
|
|||
}
|
||||
|
||||
func AesEncryptCBC(plan []byte) (string, error) {
|
||||
if (JwtSecretLen == 16 || JwtSecretLen == 24 || JwtSecretLen == 32) == false {
|
||||
return "", errors.New("JwtSecret lenght must 16/24/32.")
|
||||
}
|
||||
|
||||
// 分组秘钥
|
||||
// NewCipher该函数限制了输入k的长度必须为16, 24或者32
|
||||
block, _ := aes.NewCipher(JwtSecret)
|
||||
block, err := aes.NewCipher(JwtSecret)
|
||||
if err != nil {
|
||||
return "", exception.ErrAuthSecret
|
||||
}
|
||||
// 获取秘钥块的长度
|
||||
blockSize := block.BlockSize()
|
||||
// 补全码
|
||||
|
@ -72,17 +76,17 @@ func AesEncryptCBC(plan []byte) (string, error) {
|
|||
|
||||
func AesDecryptCBC(cryted string) (b []byte, err error) {
|
||||
if (JwtSecretLen == 16 || JwtSecretLen == 24 || JwtSecretLen == 32) == false {
|
||||
return b, errors.New("JwtSecret lenght must 16/24/32.")
|
||||
return nil, exception.ErrAuthSecret
|
||||
}
|
||||
// 转成字节数组
|
||||
crytedByte, err := base64.StdEncoding.DecodeString(cryted)
|
||||
if err != nil {
|
||||
return
|
||||
return nil, exception.ErrBase64Decode
|
||||
}
|
||||
// 分组秘钥
|
||||
block, err := aes.NewCipher(JwtSecret)
|
||||
if err != nil {
|
||||
return
|
||||
return nil, exception.ErrAuthSecret
|
||||
}
|
||||
// 获取秘钥块的长度
|
||||
blockSize := block.BlockSize()
|
||||
|
@ -121,6 +125,10 @@ func PKCS7UnPadding(origData []byte, blocksize int) []byte {
|
|||
|
||||
length := len(origData)
|
||||
unpadding := int(origData[length-1])
|
||||
|
||||
if length-unpadding <= 0 {
|
||||
return nil
|
||||
}
|
||||
return origData[:(length - unpadding)]
|
||||
}
|
||||
|
||||
|
|
|
@ -14,11 +14,32 @@ var MeshEnv *types.MeshEnv = nil
|
|||
func NewEnv() *types.MeshEnv {
|
||||
if MeshEnv == nil {
|
||||
MeshEnv = &types.MeshEnv{
|
||||
Workspace: GetEnvDefault("BlocksMesh_Workspace", "bsm"),
|
||||
Prefix: GetEnvDefault("BlocksMesh_Prefix", utils.GetCurrentPath()),
|
||||
Workspace: GetEnvDefault("BlocksMesh_Workspace", "def"),
|
||||
JwtSecretKey: GetEnvDefault("BlocksMesh_JwtSecretKey", "Cblocksmesh2022C"),
|
||||
RuntimeMode: strings.ToLower(GetEnvDefault("BlocksMesh_RuntimeMode", "dev")),
|
||||
}
|
||||
|
||||
if MeshEnv.RuntimeMode == "dev" {
|
||||
MeshEnv.Prefix = GetEnvDefault("BlocksMesh_Prefix", utils.GetCurrentPath())
|
||||
} else {
|
||||
MeshEnv.Prefix = GetEnvDefault("BlocksMesh_Prefix", "/usr/local/bsm")
|
||||
}
|
||||
}
|
||||
return MeshEnv
|
||||
}
|
||||
|
||||
// get system base env.
|
||||
func NewBaseEnv() *types.MeshEnv {
|
||||
if MeshEnv == nil {
|
||||
MeshEnv = &types.MeshEnv{
|
||||
RuntimeMode: strings.ToLower(GetEnvDefault("BlocksMesh_RuntimeMode", "dev")),
|
||||
}
|
||||
|
||||
if MeshEnv.RuntimeMode == "dev" {
|
||||
MeshEnv.Prefix = GetEnvDefault("BlocksMesh_Prefix", utils.GetCurrentPath())
|
||||
} else {
|
||||
MeshEnv.Prefix = GetEnvDefault("BlocksMesh_Prefix", "/usr/local/bsm")
|
||||
}
|
||||
}
|
||||
return MeshEnv
|
||||
}
|
||||
|
|
|
@ -2,13 +2,17 @@ package exception
|
|||
|
||||
// jwt custom error code ,begin:200
|
||||
var (
|
||||
ErrAuthPasswd = ErrorJson(201, "Password Error")
|
||||
ErrAuthNotFound = ErrorJson(202, "Auth Token Not Found")
|
||||
ErrAuthParseFail = ErrorJson(203, "Auth Parse Fail")
|
||||
ErrAuthId = ErrorJson(204, "Auth Id Not Passed")
|
||||
ErrAuthIdentity = ErrorJson(205, "Auth Identity Not Passed")
|
||||
ErrAuthTokenChanged = ErrorJson(206, "Auth Token Changed")
|
||||
ErrAuthIdType = ErrorJson(207, "Auth Id Type Error")
|
||||
ErrAuthExpire = ErrorJson(208, "Auth Token Expire")
|
||||
ErrAuthClient = ErrorJson(208, "Auth Token Client Not Passed")
|
||||
ErrAuthSecret = Errorf(200, "Auth JwtSecret Error")
|
||||
ErrBase64Decode = Errorf(201, "Auth Token Base64 Decode Error")
|
||||
ErrAuthNotFound = Errorf(202, "Auth Token Not Found")
|
||||
ErrAuthParseFail = Errorf(203, "Auth Parse Fail")
|
||||
ErrAuthId = Errorf(204, "Auth Id Not Passed")
|
||||
ErrAuthIdentity = Errorf(205, "Auth Identity Not Passed")
|
||||
ErrAuthTokenChanged = Errorf(206, "Auth Token Changed")
|
||||
ErrAuthIdType = Errorf(207, "Auth Id Type Error")
|
||||
ErrAuthExpire = Errorf(208, "Auth Token Expire")
|
||||
ErrAuthClient = Errorf(209, "Auth Token Client Not Passed")
|
||||
ErrJsonDecode = Errorf(210, "Auth JSON Decode Error")
|
||||
ErrJsonEncode = Errorf(211, "Auth JSON Encode Error")
|
||||
ErrAccountNotFound = Errorf(202, "Account Not Found")
|
||||
)
|
||||
|
|
|
@ -2,9 +2,9 @@ package exception
|
|||
|
||||
// db custom error code ,begin:300
|
||||
var (
|
||||
ErrDBFatal = ErrorJson(300, "DB Fatal error")
|
||||
ErrCacheFatal = ErrorJson(301, "Cache Fatal error")
|
||||
ErrEtcdFatal = ErrorJson(302, "Etcd Fatal error")
|
||||
ErrElasticFatal = ErrorJson(303, "Elastic Fatal error")
|
||||
ErrBlocksMQFatal = ErrorJson(304, "BlocksMQ Fatal error")
|
||||
ErrDBFatal = Errorf(300, "DB Fatal error")
|
||||
ErrCacheFatal = Errorf(301, "Cache Fatal error")
|
||||
ErrEtcdFatal = Errorf(302, "Etcd Fatal error")
|
||||
ErrElasticFatal = Errorf(303, "Elastic Fatal error")
|
||||
ErrBlocksMQFatal = Errorf(304, "BlocksMQ Fatal error")
|
||||
)
|
||||
|
|
|
@ -9,27 +9,30 @@ import (
|
|||
|
||||
var (
|
||||
// google grpc error status.
|
||||
OK = ErrorJson(0, "OK")
|
||||
ErrCanceled = ErrorJson(1, "Canceled")
|
||||
ErrUnknown = ErrorJson(2, "Unknown")
|
||||
ErrInvalidArgument = ErrorJson(3, "Invalid Argument")
|
||||
ErrDeadlineExceeded = ErrorJson(4, "Deadline Exceeded")
|
||||
ErrNotFound = ErrorJson(5, "Not Found")
|
||||
ErrAlreadyExists = ErrorJson(6, "Already Exists")
|
||||
ErrPermissionDenied = ErrorJson(7, "Permission Denied")
|
||||
ErrResourceExhausted = ErrorJson(8, "Resource Exhausted")
|
||||
ErrFailedPrecondition = ErrorJson(9, "Failed Precondition")
|
||||
ErrAborted = ErrorJson(10, "Aborted")
|
||||
ErrOutOfRange = ErrorJson(11, "Out Of Range")
|
||||
ErrUnimplemented = ErrorJson(12, "Unimplemented")
|
||||
ErrInternal = ErrorJson(13, "Internal")
|
||||
ErrUnavailable = ErrorJson(14, "Unavailable")
|
||||
ErrDataLoss = ErrorJson(15, "Data Loss")
|
||||
ErrUnauthenticated = ErrorJson(16, "Unauthenticated")
|
||||
ErrJSONMarshal = ErrorJson(17, "Marshal JSON")
|
||||
ErrJSONUnmarshal = ErrorJson(18, "Unmarshal JSON")
|
||||
OK = Errorf(0, "OK")
|
||||
ErrCanceled = Errorf(1, "Canceled")
|
||||
ErrUnknown = Errorf(2, "Unknown")
|
||||
ErrInvalidArgument = Errorf(3, "Invalid Argument")
|
||||
ErrDeadlineExceeded = Errorf(4, "Deadline Exceeded")
|
||||
ErrNotFound = Errorf(5, "Not Found")
|
||||
ErrAlreadyExists = Errorf(6, "Already Exists")
|
||||
ErrPermissionDenied = Errorf(7, "Permission Denied")
|
||||
ErrResourceExhausted = Errorf(8, "Resource Exhausted")
|
||||
ErrFailedPrecondition = Errorf(9, "Failed Precondition")
|
||||
ErrAborted = Errorf(10, "Aborted")
|
||||
ErrOutOfRange = Errorf(11, "Out Of Range")
|
||||
ErrUnimplemented = Errorf(12, "Unimplemented")
|
||||
ErrInternal = Errorf(13, "Internal")
|
||||
ErrUnavailable = Errorf(14, "Unavailable")
|
||||
ErrDataLoss = Errorf(15, "Data Loss")
|
||||
ErrUnauthenticated = Errorf(16, "Unauthenticated")
|
||||
ErrJSONMarshal = Errorf(17, "Marshal JSON")
|
||||
ErrJSONUnmarshal = Errorf(18, "Unmarshal JSON")
|
||||
ErrPasswd = Errorf(19, "Password Error")
|
||||
|
||||
ErrSmsCode = ErrorJson(20, "SMS Code Invalid")
|
||||
ErrSmsCode = Errorf(20, "SMS Code Invalid")
|
||||
ErrIdArgument = Errorf(30, "ID Invalid Argument")
|
||||
ErrIdentityArgument = Errorf(31, "Identity Invalid Argument")
|
||||
|
||||
// coustom error status
|
||||
)
|
||||
|
@ -41,7 +44,3 @@ func Error(c uint32, msg string) error {
|
|||
func Errorf(c uint32, format string, a ...interface{}) error {
|
||||
return status.New(codes.Code(c), fmt.Sprintf(format, a...)).Err()
|
||||
}
|
||||
|
||||
func ErrorJson(c uint32, msg string) error {
|
||||
return status.New(codes.Code(c), fmt.Sprintf(`{ "Code": %d, "Msg": "%s" }`, c, msg)).Err()
|
||||
}
|
||||
|
|
|
@ -2,10 +2,10 @@ package exception
|
|||
|
||||
// mq custom error code ,begin:900
|
||||
var (
|
||||
ErrMQClient = ErrorJson(900, "MQ Connect Error")
|
||||
ErrMQDispatch = ErrorJson(901, "MQ Dispatch Error")
|
||||
ErrMQProducer = ErrorJson(902, "MQ Producer Error")
|
||||
ErrMQConsumer = ErrorJson(902, "MQ Consumer Error")
|
||||
ErrMQInternal = ErrorJson(903, "MQ Internal Error")
|
||||
ErrMQStorage = ErrorJson(904, "MQ Storage Error")
|
||||
ErrMQClient = Errorf(900, "MQ Connect Error")
|
||||
ErrMQDispatch = Errorf(901, "MQ Dispatch Error")
|
||||
ErrMQProducer = Errorf(902, "MQ Producer Error")
|
||||
ErrMQConsumer = Errorf(902, "MQ Consumer Error")
|
||||
ErrMQInternal = Errorf(903, "MQ Internal Error")
|
||||
ErrMQStorage = Errorf(904, "MQ Storage Error")
|
||||
)
|
||||
|
|
|
@ -1,30 +0,0 @@
|
|||
package exception
|
||||
|
||||
// mesh custom error code ,begin:100
|
||||
var (
|
||||
// proxy
|
||||
ErrWorkerServiceNotFound = ErrorJson(100, "Service Node Not Started")
|
||||
ErrWorkerServerIsNil = ErrorJson(101, "Service Is Nil")
|
||||
ErrWorkerMethodNotFound = ErrorJson(102, "Service Method Not Found")
|
||||
ErrWorkerRequestContent = ErrorJson(103, "Worker Parse Request Content")
|
||||
ErrWorkerRequestParams = ErrorJson(104, "Worker Parse Request Params")
|
||||
|
||||
// header
|
||||
ErrInvalidHeaderParams = ErrorJson(105, "Invalid Header Params")
|
||||
|
||||
// grpc getway
|
||||
ErrWorkerFailedProxy = ErrorJson(107, "Worker gRPC proxying should never reach this stage")
|
||||
ErrWorkerGrpcProxyShould = ErrorJson(108, "Worker gRPC proxying should never reach this stage")
|
||||
ErrWorkerServerStreamNotFound = ErrorJson(109, "Worker lowLevelServerStream not exists in context")
|
||||
|
||||
// http getway
|
||||
ErrWorkerHttpReadAll = ErrorJson(110, "Worker Http Read All")
|
||||
ErrWorkerHttpResolveService = ErrorJson(111, "Worker Http Resolve Service")
|
||||
ErrWorkerHttpMarshalJSON = ErrorJson(112, "Worker Http Parameter Must JSON")
|
||||
ErrWorkerHttpUnmarshalJSON = ErrorJson(113, "Worker Http Return Not JSON")
|
||||
ErrWorkerHttpReflectInvokeRpc = ErrorJson(114, "Worker Http Reflect InvokeRpc")
|
||||
ErrWorkerHttpReflectAsDynamicMessage = ErrorJson(115, "Worker Http Reflect AsDynamicMessage")
|
||||
|
||||
// invok
|
||||
ErrServiceInvok = ErrorJson(116, "Service Invok")
|
||||
)
|
|
@ -2,12 +2,11 @@ package service
|
|||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
|
||||
"git.apinb.com/bsm-sdk/engine/encipher"
|
||||
"git.apinb.com/bsm-sdk/engine/exception"
|
||||
"git.apinb.com/bsm-sdk/engine/types"
|
||||
"git.apinb.com/bsm-sdk/engine/utils"
|
||||
"google.golang.org/grpc/metadata"
|
||||
)
|
||||
|
||||
|
@ -24,27 +23,23 @@ func ParseMetaCtx(ctx context.Context, opts *ParseOptions) (*types.JwtClaims, er
|
|||
return nil, exception.ErrAuthNotFound
|
||||
}
|
||||
|
||||
var Authorizations []string = md.Get("authorization")
|
||||
var Authorizations []string = md.Get("authorization_claims")
|
||||
if len(Authorizations) == 0 || Authorizations[0] == "" {
|
||||
return nil, exception.ErrAuthNotFound
|
||||
}
|
||||
|
||||
claims, err := encipher.ParseTokenAes(Authorizations[0])
|
||||
var claims types.JwtClaims
|
||||
err := json.Unmarshal([]byte(Authorizations[0]), &claims)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, exception.ErrAuthParseFail
|
||||
}
|
||||
|
||||
if opts != nil {
|
||||
if !strings.Contains(claims.Role, opts.RoleValue) {
|
||||
return nil, exception.ErrPermissionDenied
|
||||
}
|
||||
if opts.MustPrivateAllow {
|
||||
if utils.IsPublicIP(claims.Client) {
|
||||
return nil, exception.ErrPermissionDenied
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return claims, nil
|
||||
return &claims, nil
|
||||
|
||||
}
|
||||
|
|
|
@ -16,13 +16,14 @@ import (
|
|||
func Register(srvKey string, cfg any) {
|
||||
vars.ServiceKey = srvKey
|
||||
|
||||
print.Info("[Blocks Service] %s Starting...", vars.ServiceKey)
|
||||
// get os env.
|
||||
env.NewEnv()
|
||||
|
||||
// open side cmd.
|
||||
cmd.NewCmd()
|
||||
|
||||
print.Info("[Blocks Service] %s Starting...", vars.ServiceKey)
|
||||
|
||||
// set config args.
|
||||
args := map[string]string{
|
||||
"ServiceKey": srvKey,
|
||||
|
@ -33,7 +34,7 @@ func Register(srvKey string, cfg any) {
|
|||
// get config file.
|
||||
cf := fmt.Sprintf("%s_%s.yaml", srvKey, env.MeshEnv.RuntimeMode)
|
||||
cf = filepath.Join(env.MeshEnv.Prefix, "etc", cf)
|
||||
|
||||
print.Info("[Blocks Service] %s Config File: %s", vars.ServiceKey, cf)
|
||||
configure.LoadYamlFile(cf, args, cfg)
|
||||
|
||||
return
|
||||
|
|
40
types/db.go
40
types/db.go
|
@ -18,48 +18,54 @@ type (
|
|||
Debug bool
|
||||
}
|
||||
|
||||
// standard ID,Identity definition.
|
||||
Std_IDIdentity struct {
|
||||
ID uint `gorm:"primarykey;" json:"id"`
|
||||
Identity string `gorm:"column:identity;type:varchar(36);uniqueIndex;" json:"identity"` // 唯一标识,24位NanoID,36位为ULID
|
||||
}
|
||||
|
||||
// standard ID,Created,Updated,Deleted definition.
|
||||
Std_IICUDS struct {
|
||||
ID uint `gorm:"primarykey;"`
|
||||
Identity string `gorm:"column:identity;type:varchar(36);uniqueIndex;"` // 唯一标识,24位NanoID,36位为UUID
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
DeletedAt gorm.DeletedAt `gorm:"index";`
|
||||
Status int8 `gorm:"default:0;index;"` // 状态:默认为0,-1禁止,1为正常
|
||||
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"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index;" json:"deleted_at"`
|
||||
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;"`
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
DeletedAt gorm.DeletedAt `gorm:"index"`
|
||||
ID uint `gorm:"primarykey;" json:"id"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index;" json:"deleted_at"`
|
||||
}
|
||||
|
||||
// standard ID,Created definition.
|
||||
Std_IdCreated struct {
|
||||
ID uint `gorm:"primarykey;"`
|
||||
CreatedAt time.Time
|
||||
ID uint `gorm:"primarykey;" json:"id"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// standard PassportID,PassportIdentity definition.
|
||||
Std_Passport struct {
|
||||
PassportID uint `gorm:"column:passport_id;Index;"`
|
||||
PassportIdentity string `gorm:"column:passport_identity;type:varchar(36);Index;"` // 用户唯一标识,24位NanoID,36位为UUID
|
||||
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
|
||||
}
|
||||
|
||||
// standard ID definition.
|
||||
Std_ID struct {
|
||||
ID uint `gorm:"primarykey;"`
|
||||
ID uint `gorm:"primarykey;" json:"id"`
|
||||
}
|
||||
|
||||
// standard Identity definition.
|
||||
Std_Identity struct {
|
||||
Identity string `gorm:"column:identity;type:varchar(36);uniqueIndex;"` // 唯一标识,24位NanoID,36位为UUID
|
||||
Identity string `gorm:"column:identity;type:varchar(36);uniqueIndex;" json:"identity"` // 唯一标识,24位NanoID,36位为ULID
|
||||
}
|
||||
|
||||
// standard Status definition.
|
||||
Std_Status struct {
|
||||
Status int8 `gorm:"default:0;index;"` // 状态:默认为0,-1禁止,1为正常
|
||||
Status int8 `gorm:"default:0;index;" json:"status"` // 状态:默认为0,-1禁止,1为正常
|
||||
}
|
||||
)
|
||||
|
|
|
@ -10,6 +10,7 @@ type JwtClaims struct {
|
|||
Identity string `json:"identity"`
|
||||
Extend map[string]string `json:"extend"`
|
||||
Client string `json:"client"`
|
||||
Owner any `json:"owner"`
|
||||
Role string `json:"role"`
|
||||
ExpiresAt int64 `json:"exp"`
|
||||
}
|
||||
|
|
|
@ -1,12 +1,12 @@
|
|||
package types
|
||||
|
||||
type Etcd struct {
|
||||
Endpoints []string `json:"endpoints"`
|
||||
Tls EtcdTls `json:",optional"`
|
||||
Endpoints []string `json:"Endpoints"`
|
||||
Tls EtcdTls `json:"Tls,optional"`
|
||||
}
|
||||
|
||||
type EtcdTls struct {
|
||||
Ca string `json:"ca,optional"`
|
||||
Cert string `json:"cert,optional"`
|
||||
CertKey string `json:"cert_key,optional" `
|
||||
Ca string `json:"Ca,optional"`
|
||||
Cert string `json:"Cert,optional"`
|
||||
CertKey string `json:"CertKey,optional" `
|
||||
}
|
||||
|
|
|
@ -0,0 +1,56 @@
|
|||
package types
|
||||
|
||||
type Message struct {
|
||||
TimeSequence int64 //消息创建的时间戳
|
||||
SessionIdent string // 会话唯一标识
|
||||
SenderId int64
|
||||
SenderIdentity string
|
||||
TargetId int64
|
||||
TargetIdentity string
|
||||
GroupId int64 //群组唯一ID,在群聊消息的时候使用到。不使用时则为空
|
||||
GroupIdentity string //群组唯一码,在群聊消息的时候使用到。不使用时则为空
|
||||
MsgType int32 //0异常提示,1单聊,2群聊,3系统
|
||||
BodyType int32 //正文类型:0文本,1图片,2,视频,3.....
|
||||
Body string
|
||||
Status int32 //消息状态:0待续,1存储成功,2送达确认,3已读确认,-1撤回
|
||||
}
|
||||
|
||||
type ChatMessage struct {
|
||||
TimeSequence int64 //消息创建的时间戳
|
||||
SessionIdent string // 会话唯一标识
|
||||
SenderId int64
|
||||
SenderIdentity string
|
||||
TargetId int64
|
||||
TargetIdentity string
|
||||
BodyType int32 //正文类型:0文本,1图片,2,视频,3.....
|
||||
Body string
|
||||
Status int32 //消息状态:0待续,1存储成功,2送达确认,3已读确认,-1撤回
|
||||
}
|
||||
|
||||
type GroupMessage struct {
|
||||
TimeSequence int64 //消息创建的时间戳
|
||||
GroupId int64 //群组唯一ID,在群聊消息的时候使用到。不使用时则为空
|
||||
GroupIdentity string //群组唯一标识,在群聊消息的时候使用到。不使用时则为空
|
||||
SenderId int64
|
||||
SenderIdentity string
|
||||
BodyType int32 //正文类型:0文本,1图片,2,视频,3.....
|
||||
Body string
|
||||
Status int32 //消息状态:0待续,1存储成功,2送达确认,3已读确认,-1撤回
|
||||
}
|
||||
|
||||
type SystemMessage struct {
|
||||
TimeSequence int64 //消息创建的时间戳
|
||||
TargetId int64
|
||||
TargetIdentity string
|
||||
BodyType int32 //正文类型:0文本,1图片,2,视频,3.....
|
||||
Body string
|
||||
Status int32 //消息状态:0待续,1存储成功,2送达确认,3已读确认,-1撤回
|
||||
}
|
||||
|
||||
type EventMessage struct {
|
||||
TimeSequence int64 //消息创建的时间戳
|
||||
TargetId int64
|
||||
TargetIdentity string
|
||||
EventType int32 //事件类型:0 正在输入,已送达...
|
||||
Status int32 //消息状态:0待续,1存储成功,2送达确认,3已读确认,-1撤回
|
||||
}
|
|
@ -2,21 +2,21 @@ package utils
|
|||
|
||||
import (
|
||||
"math"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// 字符串转Int
|
||||
// intStr:数字的字符串
|
||||
//
|
||||
// intStr:数字的字符串
|
||||
func String2Int(intStr string) (intNum int) {
|
||||
intNum, _ = strconv.Atoi(intStr)
|
||||
return
|
||||
}
|
||||
|
||||
// 字符串转Int64
|
||||
// intStr:数字的字符串
|
||||
//
|
||||
// intStr:数字的字符串
|
||||
func String2Int64(intStr string) (int64Num int64) {
|
||||
intNum, _ := strconv.Atoi(intStr)
|
||||
int64Num = int64(intNum)
|
||||
|
@ -24,14 +24,16 @@ func String2Int64(intStr string) (int64Num int64) {
|
|||
}
|
||||
|
||||
// 字符串转Float64
|
||||
// floatStr:小数点数字的字符串
|
||||
//
|
||||
// floatStr:小数点数字的字符串
|
||||
func String2Float64(floatStr string) (floatNum float64) {
|
||||
floatNum, _ = strconv.ParseFloat(floatStr, 64)
|
||||
return
|
||||
}
|
||||
|
||||
// 字符串转Float32
|
||||
// floatStr:小数点数字的字符串
|
||||
//
|
||||
// floatStr:小数点数字的字符串
|
||||
func String2Float32(floatStr string) (floatNum float32) {
|
||||
floatNum64, _ := strconv.ParseFloat(floatStr, 32)
|
||||
floatNum = float32(floatNum64)
|
||||
|
@ -39,14 +41,16 @@ func String2Float32(floatStr string) (floatNum float32) {
|
|||
}
|
||||
|
||||
// Int转字符串
|
||||
// intNum:数字字符串
|
||||
//
|
||||
// intNum:数字字符串
|
||||
func Int2String(intNum int) (intStr string) {
|
||||
intStr = strconv.Itoa(intNum)
|
||||
return
|
||||
}
|
||||
|
||||
// Int64转字符串
|
||||
// intNum:数字字符串
|
||||
//
|
||||
// intNum:数字字符串
|
||||
func Int642String(intNum int64) (int64Str string) {
|
||||
//10, 代表10进制
|
||||
int64Str = strconv.FormatInt(intNum, 10)
|
||||
|
@ -54,8 +58,9 @@ func Int642String(intNum int64) (int64Str string) {
|
|||
}
|
||||
|
||||
// Float64转字符串
|
||||
// floatNum:float64数字
|
||||
// prec:精度位数(不传则默认float数字精度)
|
||||
//
|
||||
// floatNum:float64数字
|
||||
// prec:精度位数(不传则默认float数字精度)
|
||||
func Float64ToString(floatNum float64, prec ...int) (floatStr string) {
|
||||
if len(prec) > 0 {
|
||||
floatStr = strconv.FormatFloat(floatNum, 'f', prec[0], 64)
|
||||
|
@ -66,8 +71,9 @@ func Float64ToString(floatNum float64, prec ...int) (floatStr string) {
|
|||
}
|
||||
|
||||
// Float32转字符串
|
||||
// floatNum:float32数字
|
||||
// prec:精度位数(不传则默认float数字精度)
|
||||
//
|
||||
// floatNum:float32数字
|
||||
// prec:精度位数(不传则默认float数字精度)
|
||||
func Float32ToString(floatNum float32, prec ...int) (floatStr string) {
|
||||
if len(prec) > 0 {
|
||||
floatStr = strconv.FormatFloat(float64(floatNum), 'f', prec[0], 32)
|
||||
|
@ -90,15 +96,6 @@ func BinaryToDecimal(bit string) (num int) {
|
|||
return
|
||||
}
|
||||
|
||||
// BytesToString 0 拷贝转换 slice byte 为 string
|
||||
func BytesToString(b []byte) (s string) {
|
||||
_bptr := (*reflect.SliceHeader)(unsafe.Pointer(&b))
|
||||
_sptr := (*reflect.StringHeader)(unsafe.Pointer(&s))
|
||||
_sptr.Data = _bptr.Data
|
||||
_sptr.Len = _bptr.Len
|
||||
return s
|
||||
}
|
||||
|
||||
// interface to string
|
||||
func AnyToString(in any) (s string) {
|
||||
if in == nil {
|
||||
|
|
|
@ -1,26 +1,10 @@
|
|||
package utils
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jaevor/go-nanoid"
|
||||
ulid "github.com/oklog/ulid/v2"
|
||||
)
|
||||
|
||||
func NanoID() string {
|
||||
nanoid, _ := nanoid.CustomASCII("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", 21)
|
||||
return nanoid()
|
||||
}
|
||||
|
||||
func NanoIDInt() (id int64, err error) {
|
||||
decenaryID, err := nanoid.CustomASCII("0123456789", 20)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
id, err = strconv.ParseInt(decenaryID(), 10, 64)
|
||||
return
|
||||
}
|
||||
|
||||
func UUID() string {
|
||||
return uuid.NewString()
|
||||
// remove nanoid,uuid,replace to ulid
|
||||
func ULID() string {
|
||||
return ulid.Make().String()
|
||||
}
|
||||
|
|
|
@ -99,7 +99,7 @@ func HttpPost(url string, header map[string]string, data []byte) ([]byte, error)
|
|||
}
|
||||
|
||||
request.Header.Set("Content-Type", "application/json;charset=UTF-8")
|
||||
request.Header.Set("Request-Id", NanoID())
|
||||
request.Header.Set("Request-Id", ULID())
|
||||
|
||||
for key, val := range header {
|
||||
request.Header.Set(key, val)
|
||||
|
|
|
@ -1,42 +1,49 @@
|
|||
package utils
|
||||
|
||||
import (
|
||||
"math/rand"
|
||||
"time"
|
||||
"math/rand/v2"
|
||||
)
|
||||
|
||||
//随机生成字符串
|
||||
// 随机生成字符串
|
||||
func RandomString(l int) string {
|
||||
str := "0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
|
||||
bytes := []byte(str)
|
||||
var result []byte = make([]byte, 0, l)
|
||||
r := rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
for i := 0; i < l; i++ {
|
||||
result = append(result, bytes[r.Intn(len(bytes))])
|
||||
result = append(result, bytes[rand.IntN(len(bytes))])
|
||||
}
|
||||
return BytesToString(result)
|
||||
return string(result)
|
||||
}
|
||||
|
||||
//随机生成纯字符串
|
||||
// 随机生成纯字符串
|
||||
func RandomPureString(l int) string {
|
||||
str := "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
|
||||
bytes := []byte(str)
|
||||
var result []byte = make([]byte, 0, l)
|
||||
r := rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
for i := 0; i < l; i++ {
|
||||
result = append(result, bytes[r.Intn(len(bytes))])
|
||||
result = append(result, bytes[rand.IntN(len(bytes))])
|
||||
}
|
||||
return BytesToString(result)
|
||||
return string(result)
|
||||
}
|
||||
|
||||
//随机生成数字字符串
|
||||
// 随机生成纯大写字符串
|
||||
func RandomPureUpString(l int) string {
|
||||
str := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||
bytes := []byte(str)
|
||||
var result []byte = make([]byte, 0, l)
|
||||
for i := 0; i < l; i++ {
|
||||
result = append(result, bytes[rand.IntN(len(bytes))])
|
||||
}
|
||||
return string(result)
|
||||
}
|
||||
|
||||
// 随机生成数字字符串
|
||||
func RandomNumber(l int) string {
|
||||
str := "0123456789"
|
||||
bytes := []byte(str)
|
||||
var result []byte
|
||||
r := rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
for i := 0; i < l; i++ {
|
||||
result = append(result, bytes[r.Intn(len(bytes))])
|
||||
result = append(result, bytes[rand.IntN(len(bytes))])
|
||||
}
|
||||
return BytesToString(result)
|
||||
return string(result)
|
||||
}
|
||||
|
|
|
@ -0,0 +1,8 @@
|
|||
package vars
|
||||
|
||||
const (
|
||||
// NormalStatus .
|
||||
NormalStatus = 1
|
||||
// DisabledStatus .
|
||||
DisabledStatus = -1
|
||||
)
|
Loading…
Reference in New Issue