Compare commits

...

37 Commits

Author SHA1 Message Date
yanweidong fe3e02370c fix,upd module 2024-12-03 18:53:11 +08:00
yanweidong 3dfadd7a30 dev 2024-12-02 11:41:17 +08:00
yanweidong 175848c47e dev 2024-12-02 11:28:37 +08:00
yanweidong 839d85d493 add err code 2024-10-15 12:53:06 +08:00
yanweidong 3b5719bc91 更新 types/etcd.go 2024-10-03 20:52:35 +08:00
yanweidong ec2bf11981 更新 types/etcd.go 2024-10-03 20:47:47 +08:00
yanweidong 9bb2a1d730 更新 env/env.go 2024-10-03 20:39:18 +08:00
yanweidong d645a49c97 更新 types/etcd.go 2024-10-03 20:35:48 +08:00
yanweidong a8efe29c7f fix env prefix die 2024-09-29 11:58:44 +08:00
yanweidong 3d609bfba8 remove nanoid,uuid,replace to ulid 2024-09-20 14:46:46 +08:00
yanweidong 8537320513 dev 2024-09-20 14:45:34 +08:00
david 0be9490840 dev 2024-09-17 21:57:37 +08:00
david 84d6a9d034 dev 2024-09-17 21:27:12 +08:00
david 59118cf8f2 dev 2024-09-17 18:54:13 +08:00
yanweidong aada90ea78 fix types.db 2024-07-02 11:01:37 +08:00
yanweidong 28ad46d403 fix jwt 2024-06-28 11:29:46 +08:00
david 31c602dcc5 Merge branch 'master' of https://git.apinb.com/bsm-sdk/engine 2024-06-24 16:24:38 +08:00
david 52e78a321e add vars.Status 2024-06-24 16:24:33 +08:00
yanweidong 6cac60f15e add ULID 2024-06-14 17:23:24 +08:00
yanweidong 2d40fc38ce add exception code 2024-06-05 15:46:57 +08:00
yanweidong f83797a746 clean go mod 2024-05-29 14:48:41 +08:00
zhaoxiaorong c255ffb558 fix NanoIDInt length 2024-04-19 16:35:27 +08:00
phpstudyer 4003529b5c 增加database 配置DisableForeignKeyConstraintWhenMigrating: true 2024-03-22 12:12:17 +08:00
yanweidong 25ecea7e09 fix bug 2024-03-15 15:28:53 +08:00
yanweidong 76fd17c0f0 dev 2024-03-15 15:18:54 +08:00
yanweidong 07626c9d54 fix message type 2024-03-08 14:17:19 +08:00
yanweidong ddc1eb90d8 Merge branch 'master' of https://git.apinb.com/bsm-sdk/engine 2024-03-05 14:53:44 +08:00
yanweidong 2ef1de8118 dev 2024-03-05 14:53:37 +08:00
david 29fb426c60 fix jwtClaims + owner 2024-02-29 22:14:56 +08:00
david f2f179d984 fix jwtClaims + owneridentity 2024-02-29 22:11:36 +08:00
yanweidong 26048b1b41 fix encipher return errors 2024-02-28 13:47:23 +08:00
yanweidong 8bff8e7377 fix errors code. 2024-02-28 13:40:34 +08:00
yanweidong 983545b0d7 fix encipher.New 2024-02-28 12:30:42 +08:00
david 7575423cff Merge branch 'master' of https://git.apinb.com/bsm-sdk/engine 2024-02-21 20:58:37 +08:00
david acaaa8d6ed update go 1.22 2024-02-21 20:58:31 +08:00
david a357fa225b dev 2024-02-21 20:33:47 +08:00
yanweidong 31a80eb904 fix aes unpk 2024-02-20 16:52:41 +08:00
18 changed files with 232 additions and 111 deletions

30
database/sql/ext.go Normal file
View File

@ -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 ")
}

View File

@ -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{ gormDb, err := gorm.Open(postgres.New(postgres.Config{
DSN: dsn, DSN: dsn,
// PreferSimpleProtocol: true, disables implicit prepared statement usage // PreferSimpleProtocol: true, disables implicit prepared statement usage
}), &gorm.Config{ }), &gorm.Config{
Logger: newLogger, //Logger:newLogger,
DisableForeignKeyConstraintWhenMigrating: true,
NamingStrategy: schema.NamingStrategy{ NamingStrategy: schema.NamingStrategy{
SingularTable: true, // 使用单数表名,启用该选项,此时,`User` 的表名应该是 `t_user` SingularTable: true, // 使用单数表名,启用该选项,此时,`User` 的表名应该是 `t_user`
}}) }})

View File

@ -6,7 +6,6 @@ import (
"crypto/cipher" "crypto/cipher"
"encoding/base64" "encoding/base64"
"encoding/json" "encoding/json"
"errors"
"strings" "strings"
"time" "time"
@ -22,25 +21,29 @@ var (
JwtSecretLen int JwtSecretLen int
) )
func New() { func New(token string) {
JwtSecret = []byte(env.MeshEnv.JwtSecretKey) JwtSecret = []byte(token)
JwtSecretLen = len(env.MeshEnv.JwtSecretKey) 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) expireTime := time.Now().Add(vars.JwtExpireDay)
claims := types.JwtClaims{ claims := types.JwtClaims{
ID: id, ID: id,
Identity: identity, Identity: identity,
Extend: extend,
Client: client, Client: client,
Extend: extend,
Owner: owner,
Role: role, Role: role,
ExpiresAt: expireTime.Unix(), ExpiresAt: expireTime.Unix(),
} }
byte, err := json.Marshal(claims) byte, err := json.Marshal(claims)
if err != nil { if err != nil {
return "", err return "", exception.ErrJsonEncode
} }
token, err := AesEncryptCBC(byte) 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) { 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 // NewCipher该函数限制了输入k的长度必须为16, 24或者32
block, _ := aes.NewCipher(JwtSecret) block, err := aes.NewCipher(JwtSecret)
if err != nil {
return "", exception.ErrAuthSecret
}
// 获取秘钥块的长度 // 获取秘钥块的长度
blockSize := block.BlockSize() blockSize := block.BlockSize()
// 补全码 // 补全码
@ -72,17 +76,17 @@ func AesEncryptCBC(plan []byte) (string, error) {
func AesDecryptCBC(cryted string) (b []byte, err error) { func AesDecryptCBC(cryted string) (b []byte, err error) {
if (JwtSecretLen == 16 || JwtSecretLen == 24 || JwtSecretLen == 32) == false { 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) crytedByte, err := base64.StdEncoding.DecodeString(cryted)
if err != nil { if err != nil {
return return nil, exception.ErrBase64Decode
} }
// 分组秘钥 // 分组秘钥
block, err := aes.NewCipher(JwtSecret) block, err := aes.NewCipher(JwtSecret)
if err != nil { if err != nil {
return return nil, exception.ErrAuthSecret
} }
// 获取秘钥块的长度 // 获取秘钥块的长度
blockSize := block.BlockSize() blockSize := block.BlockSize()
@ -121,6 +125,10 @@ func PKCS7UnPadding(origData []byte, blocksize int) []byte {
length := len(origData) length := len(origData)
unpadding := int(origData[length-1]) unpadding := int(origData[length-1])
if length-unpadding <= 0 {
return nil
}
return origData[:(length - unpadding)] return origData[:(length - unpadding)]
} }

25
env/env.go vendored
View File

@ -14,11 +14,32 @@ var MeshEnv *types.MeshEnv = nil
func NewEnv() *types.MeshEnv { func NewEnv() *types.MeshEnv {
if MeshEnv == nil { if MeshEnv == nil {
MeshEnv = &types.MeshEnv{ MeshEnv = &types.MeshEnv{
Workspace: GetEnvDefault("BlocksMesh_Workspace", "bsm"), Workspace: GetEnvDefault("BlocksMesh_Workspace", "def"),
Prefix: GetEnvDefault("BlocksMesh_Prefix", utils.GetCurrentPath()),
JwtSecretKey: GetEnvDefault("BlocksMesh_JwtSecretKey", "Cblocksmesh2022C"), JwtSecretKey: GetEnvDefault("BlocksMesh_JwtSecretKey", "Cblocksmesh2022C"),
RuntimeMode: strings.ToLower(GetEnvDefault("BlocksMesh_RuntimeMode", "dev")), 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 return MeshEnv
} }

View File

@ -2,7 +2,8 @@ package exception
// jwt custom error code ,begin:200 // jwt custom error code ,begin:200
var ( var (
ErrAuthPasswd = Errorf(201, "Password Error") ErrAuthSecret = Errorf(200, "Auth JwtSecret Error")
ErrBase64Decode = Errorf(201, "Auth Token Base64 Decode Error")
ErrAuthNotFound = Errorf(202, "Auth Token Not Found") ErrAuthNotFound = Errorf(202, "Auth Token Not Found")
ErrAuthParseFail = Errorf(203, "Auth Parse Fail") ErrAuthParseFail = Errorf(203, "Auth Parse Fail")
ErrAuthId = Errorf(204, "Auth Id Not Passed") ErrAuthId = Errorf(204, "Auth Id Not Passed")
@ -10,5 +11,8 @@ var (
ErrAuthTokenChanged = Errorf(206, "Auth Token Changed") ErrAuthTokenChanged = Errorf(206, "Auth Token Changed")
ErrAuthIdType = Errorf(207, "Auth Id Type Error") ErrAuthIdType = Errorf(207, "Auth Id Type Error")
ErrAuthExpire = Errorf(208, "Auth Token Expire") ErrAuthExpire = Errorf(208, "Auth Token Expire")
ErrAuthClient = Errorf(208, "Auth Token Client Not Passed") 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")
) )

View File

@ -28,8 +28,11 @@ var (
ErrUnauthenticated = Errorf(16, "Unauthenticated") ErrUnauthenticated = Errorf(16, "Unauthenticated")
ErrJSONMarshal = Errorf(17, "Marshal JSON") ErrJSONMarshal = Errorf(17, "Marshal JSON")
ErrJSONUnmarshal = Errorf(18, "Unmarshal JSON") ErrJSONUnmarshal = Errorf(18, "Unmarshal JSON")
ErrPasswd = Errorf(19, "Password Error")
ErrSmsCode = Errorf(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 // coustom error status
) )

2
go.mod
View File

@ -1,3 +1,3 @@
module git.apinb.com/bsm-sdk/engine module git.apinb.com/bsm-sdk/engine
go 1.21 go 1.23.3

View File

@ -2,12 +2,11 @@ package service
import ( import (
"context" "context"
"encoding/json"
"strings" "strings"
"git.apinb.com/bsm-sdk/engine/encipher"
"git.apinb.com/bsm-sdk/engine/exception" "git.apinb.com/bsm-sdk/engine/exception"
"git.apinb.com/bsm-sdk/engine/types" "git.apinb.com/bsm-sdk/engine/types"
"git.apinb.com/bsm-sdk/engine/utils"
"google.golang.org/grpc/metadata" "google.golang.org/grpc/metadata"
) )
@ -24,27 +23,23 @@ func ParseMetaCtx(ctx context.Context, opts *ParseOptions) (*types.JwtClaims, er
return nil, exception.ErrAuthNotFound return nil, exception.ErrAuthNotFound
} }
var Authorizations []string = md.Get("authorization") var Authorizations []string = md.Get("authorization_claims")
if len(Authorizations) == 0 || Authorizations[0] == "" { if len(Authorizations) == 0 || Authorizations[0] == "" {
return nil, exception.ErrAuthNotFound return nil, exception.ErrAuthNotFound
} }
claims, err := encipher.ParseTokenAes(Authorizations[0]) var claims types.JwtClaims
err := json.Unmarshal([]byte(Authorizations[0]), &claims)
if err != nil { if err != nil {
return nil, err return nil, exception.ErrAuthParseFail
} }
if opts != nil { if opts != nil {
if !strings.Contains(claims.Role, opts.RoleValue) { if !strings.Contains(claims.Role, opts.RoleValue) {
return nil, exception.ErrPermissionDenied return nil, exception.ErrPermissionDenied
} }
if opts.MustPrivateAllow {
if utils.IsPublicIP(claims.Client) {
return nil, exception.ErrPermissionDenied
}
}
} }
return claims, nil return &claims, nil
} }

View File

@ -34,7 +34,7 @@ func Register(srvKey string, cfg any) {
// get config file. // get config file.
cf := fmt.Sprintf("%s_%s.yaml", srvKey, env.MeshEnv.RuntimeMode) cf := fmt.Sprintf("%s_%s.yaml", srvKey, env.MeshEnv.RuntimeMode)
cf = filepath.Join(env.MeshEnv.Prefix, "etc", cf) cf = filepath.Join(env.MeshEnv.Prefix, "etc", cf)
print.Info("[Blocks Service] %s Config File: %s", vars.ServiceKey, cf)
configure.LoadYamlFile(cf, args, cfg) configure.LoadYamlFile(cf, args, cfg)
return return

View File

@ -18,48 +18,54 @@ type (
Debug bool 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. // standard ID,Created,Updated,Deleted definition.
Std_IICUDS struct { Std_IICUDS struct {
ID uint `gorm:"primarykey;"` ID uint `gorm:"primarykey;" json:"id"`
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
CreatedAt time.Time CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index";` DeletedAt gorm.DeletedAt `gorm:"index;" json:"deleted_at"`
Status int8 `gorm:"default:0;index;"` // 状态默认为0-1禁止1为正常 Status int8 `gorm:"default:0;index;" json:"status"` // 状态默认为0-1禁止1为正常
} }
// standard ID,Identity,Created,Updated,Deleted,Status definition. // standard ID,Identity,Created,Updated,Deleted,Status definition.
Std_ICUD struct { Std_ICUD struct {
ID uint `gorm:"primarykey;"` ID uint `gorm:"primarykey;" json:"id"`
CreatedAt time.Time CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index"` DeletedAt gorm.DeletedAt `gorm:"index;" json:"deleted_at"`
} }
// standard ID,Created definition. // standard ID,Created definition.
Std_IdCreated struct { Std_IdCreated struct {
ID uint `gorm:"primarykey;"` ID uint `gorm:"primarykey;" json:"id"`
CreatedAt time.Time CreatedAt time.Time `json:"created_at"`
} }
// standard PassportID,PassportIdentity definition. // standard PassportID,PassportIdentity definition.
Std_Passport struct { Std_Passport struct {
PassportID uint `gorm:"column:passport_id;Index;"` PassportID uint `gorm:"column:passport_id;Index;" json:"passport_id"`
PassportIdentity string `gorm:"column:passport_identity;type:varchar(36);Index;"` // 用户唯一标识24位NanoID,36位为UUID PassportIdentity string `gorm:"column:passport_identity;type:varchar(36);Index;" json:"passport_identity"` // 用户唯一标识24位NanoID,36位为ULID
} }
// standard ID definition. // standard ID definition.
Std_ID struct { Std_ID struct {
ID uint `gorm:"primarykey;"` ID uint `gorm:"primarykey;" json:"id"`
} }
// standard Identity definition. // standard Identity definition.
Std_Identity struct { 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. // standard Status definition.
Std_Status struct { Std_Status struct {
Status int8 `gorm:"default:0;index;"` // 状态默认为0-1禁止1为正常 Status int8 `gorm:"default:0;index;" json:"status"` // 状态默认为0-1禁止1为正常
} }
) )

View File

@ -10,6 +10,7 @@ type JwtClaims struct {
Identity string `json:"identity"` Identity string `json:"identity"`
Extend map[string]string `json:"extend"` Extend map[string]string `json:"extend"`
Client string `json:"client"` Client string `json:"client"`
Owner any `json:"owner"`
Role string `json:"role"` Role string `json:"role"`
ExpiresAt int64 `json:"exp"` ExpiresAt int64 `json:"exp"`
} }

View File

@ -1,12 +1,12 @@
package types package types
type Etcd struct { type Etcd struct {
Endpoints []string `json:"endpoints"` Endpoints []string `json:"Endpoints"`
Tls EtcdTls `json:",optional"` Tls EtcdTls `json:"Tls,optional"`
} }
type EtcdTls struct { type EtcdTls struct {
Ca string `json:"ca,optional"` Ca string `json:"Ca,optional"`
Cert string `json:"cert,optional"` Cert string `json:"Cert,optional"`
CertKey string `json:"cert_key,optional" ` CertKey string `json:"CertKey,optional" `
} }

56
types/mcs.go Normal file
View File

@ -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撤回
}

View File

@ -2,13 +2,12 @@ package utils
import ( import (
"math" "math"
"reflect"
"strconv" "strconv"
"strings" "strings"
"unsafe"
) )
// 字符串转Int // 字符串转Int
//
// intStr数字的字符串 // intStr数字的字符串
func String2Int(intStr string) (intNum int) { func String2Int(intStr string) (intNum int) {
intNum, _ = strconv.Atoi(intStr) intNum, _ = strconv.Atoi(intStr)
@ -16,6 +15,7 @@ func String2Int(intStr string) (intNum int) {
} }
// 字符串转Int64 // 字符串转Int64
//
// intStr数字的字符串 // intStr数字的字符串
func String2Int64(intStr string) (int64Num int64) { func String2Int64(intStr string) (int64Num int64) {
intNum, _ := strconv.Atoi(intStr) intNum, _ := strconv.Atoi(intStr)
@ -24,6 +24,7 @@ func String2Int64(intStr string) (int64Num int64) {
} }
// 字符串转Float64 // 字符串转Float64
//
// floatStr小数点数字的字符串 // floatStr小数点数字的字符串
func String2Float64(floatStr string) (floatNum float64) { func String2Float64(floatStr string) (floatNum float64) {
floatNum, _ = strconv.ParseFloat(floatStr, 64) floatNum, _ = strconv.ParseFloat(floatStr, 64)
@ -31,6 +32,7 @@ func String2Float64(floatStr string) (floatNum float64) {
} }
// 字符串转Float32 // 字符串转Float32
//
// floatStr小数点数字的字符串 // floatStr小数点数字的字符串
func String2Float32(floatStr string) (floatNum float32) { func String2Float32(floatStr string) (floatNum float32) {
floatNum64, _ := strconv.ParseFloat(floatStr, 32) floatNum64, _ := strconv.ParseFloat(floatStr, 32)
@ -39,6 +41,7 @@ func String2Float32(floatStr string) (floatNum float32) {
} }
// Int转字符串 // Int转字符串
//
// intNum数字字符串 // intNum数字字符串
func Int2String(intNum int) (intStr string) { func Int2String(intNum int) (intStr string) {
intStr = strconv.Itoa(intNum) intStr = strconv.Itoa(intNum)
@ -46,6 +49,7 @@ func Int2String(intNum int) (intStr string) {
} }
// Int64转字符串 // Int64转字符串
//
// intNum数字字符串 // intNum数字字符串
func Int642String(intNum int64) (int64Str string) { func Int642String(intNum int64) (int64Str string) {
//10, 代表10进制 //10, 代表10进制
@ -54,6 +58,7 @@ func Int642String(intNum int64) (int64Str string) {
} }
// Float64转字符串 // Float64转字符串
//
// floatNumfloat64数字 // floatNumfloat64数字
// prec精度位数不传则默认float数字精度 // prec精度位数不传则默认float数字精度
func Float64ToString(floatNum float64, prec ...int) (floatStr string) { func Float64ToString(floatNum float64, prec ...int) (floatStr string) {
@ -66,6 +71,7 @@ func Float64ToString(floatNum float64, prec ...int) (floatStr string) {
} }
// Float32转字符串 // Float32转字符串
//
// floatNumfloat32数字 // floatNumfloat32数字
// prec精度位数不传则默认float数字精度 // prec精度位数不传则默认float数字精度
func Float32ToString(floatNum float32, prec ...int) (floatStr string) { func Float32ToString(floatNum float32, prec ...int) (floatStr string) {
@ -90,15 +96,6 @@ func BinaryToDecimal(bit string) (num int) {
return 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 // interface to string
func AnyToString(in any) (s string) { func AnyToString(in any) (s string) {
if in == nil { if in == nil {

View File

@ -1,26 +1,10 @@
package utils package utils
import ( import (
"strconv" ulid "github.com/oklog/ulid/v2"
"github.com/google/uuid"
"github.com/jaevor/go-nanoid"
) )
func NanoID() string { // remove nanoid,uuid,replace to ulid
nanoid, _ := nanoid.CustomASCII("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", 21) func ULID() string {
return nanoid() return ulid.Make().String()
}
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()
} }

View File

@ -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("Content-Type", "application/json;charset=UTF-8")
request.Header.Set("Request-Id", NanoID()) request.Header.Set("Request-Id", ULID())
for key, val := range header { for key, val := range header {
request.Header.Set(key, val) request.Header.Set(key, val)

View File

@ -1,8 +1,7 @@
package utils package utils
import ( import (
"math/rand" "math/rand/v2"
"time"
) )
// 随机生成字符串 // 随机生成字符串
@ -10,11 +9,10 @@ func RandomString(l int) string {
str := "0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz" str := "0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
bytes := []byte(str) bytes := []byte(str)
var result []byte = make([]byte, 0, l) var result []byte = make([]byte, 0, l)
r := rand.New(rand.NewSource(time.Now().UnixNano()))
for i := 0; i < l; i++ { 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)
} }
// 随机生成纯字符串 // 随机生成纯字符串
@ -22,11 +20,21 @@ func RandomPureString(l int) string {
str := "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz" str := "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
bytes := []byte(str) bytes := []byte(str)
var result []byte = make([]byte, 0, l) var result []byte = make([]byte, 0, l)
r := rand.New(rand.NewSource(time.Now().UnixNano()))
for i := 0; i < l; i++ { 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)
} }
// 随机生成数字字符串 // 随机生成数字字符串
@ -34,9 +42,8 @@ func RandomNumber(l int) string {
str := "0123456789" str := "0123456789"
bytes := []byte(str) bytes := []byte(str)
var result []byte var result []byte
r := rand.New(rand.NewSource(time.Now().UnixNano()))
for i := 0; i < l; i++ { 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)
} }

8
vars/status.go Normal file
View File

@ -0,0 +1,8 @@
package vars
const (
// NormalStatus .
NormalStatus = 1
// DisabledStatus .
DisabledStatus = -1
)