提交 62016f9a authored 作者: mooncake9527's avatar mooncake9527

update

上级 c0316c80
...@@ -5,10 +5,12 @@ import ( ...@@ -5,10 +5,12 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"net/http" "net/http"
"time"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"gitlab.wanzhuangkj.com/tush/xpkg/errcode" "gitlab.wanzhuangkj.com/tush/xpkg/errcode"
"gitlab.wanzhuangkj.com/tush/xpkg/gin/xctx"
ctxUtil "gitlab.wanzhuangkj.com/tush/xpkg/gin/xctx" ctxUtil "gitlab.wanzhuangkj.com/tush/xpkg/gin/xctx"
"gitlab.wanzhuangkj.com/tush/xpkg/logger" "gitlab.wanzhuangkj.com/tush/xpkg/logger"
"gitlab.wanzhuangkj.com/tush/xpkg/xerrors/xerror" "gitlab.wanzhuangkj.com/tush/xpkg/xerrors/xerror"
...@@ -18,15 +20,19 @@ const CustomErrorCode = 0 ...@@ -18,15 +20,19 @@ const CustomErrorCode = 0
// Result output data format // Result output data format
type Result struct { type Result struct {
Code int `json:"code"` Code int `json:"code" example:"1"`
Msg string `json:"message"` Msg string `json:"message" example:"OK"`
Data interface{} `json:"data"` Data interface{} `json:"data"`
TimeStamp int64 `json:"timestamp" example:"1718850053"`
TraceID string `json:"traceID" example:"7f0000016673920576f0659c620086b0"`
} }
func newResp(code int, msg string, data interface{}) *Result { func newResp(c *gin.Context, code int, msg string, data interface{}) *Result {
resp := &Result{ resp := &Result{
Code: code, Code: code,
Msg: msg, Msg: msg,
TimeStamp: time.Now().Unix(),
TraceID: xctx.GetGinCtxTid(c),
} }
// ensure that the data field is not nil on return, note that it is not nil when resp.data=[]interface {}, it is serialized to null // ensure that the data field is not nil on return, note that it is not nil when resp.data=[]interface {}, it is serialized to null
...@@ -64,7 +70,7 @@ func respJSONWithStatusCode(c *gin.Context, code int, msg string, data ...interf ...@@ -64,7 +70,7 @@ func respJSONWithStatusCode(c *gin.Context, code int, msg string, data ...interf
if len(data) > 0 { if len(data) > 0 {
firstData = data[0] firstData = data[0]
} }
resp := newResp(code, msg, firstData) resp := newResp(c, code, msg, firstData)
writeJSON(c, code, resp) writeJSON(c, code, resp)
} }
...@@ -131,10 +137,10 @@ func Out(c *gin.Context, err *errcode.Error, data ...interface{}) { ...@@ -131,10 +137,10 @@ func Out(c *gin.Context, err *errcode.Error, data ...interface{}) {
// status code flat 200, custom error codes in data.code // status code flat 200, custom error codes in data.code
func respJSONWith200(c *gin.Context, code int, msg string, data ...interface{}) { func respJSONWith200(c *gin.Context, code int, msg string, data ...interface{}) {
if len(data) > 0 { if len(data) > 0 {
writeJSON(c, http.StatusOK, newResp(code, msg, data[0])) writeJSON(c, http.StatusOK, newResp(c, code, msg, data[0]))
return return
} }
resp := newResp(code, msg, nil) resp := newResp(c, code, msg, nil)
writeJSON(c, http.StatusOK, resp) writeJSON(c, http.StatusOK, resp)
} }
......
...@@ -3,7 +3,7 @@ package xctx ...@@ -3,7 +3,7 @@ package xctx
import ( import (
"context" "context"
xsf "gitlab.wanzhuangkj.com/tush/xpkg/utils/xsnowflake" xsf "gitlab.wanzhuangkj.com/tush/xpkg/utils/xsf"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/spf13/cast" "github.com/spf13/cast"
...@@ -75,34 +75,34 @@ func CtxTraceIDField(c context.Context) zap.Field { ...@@ -75,34 +75,34 @@ func CtxTraceIDField(c context.Context) zap.Field {
return zap.String(ContextRequestIDKey, CtxRequestID(c)) return zap.String(ContextRequestIDKey, CtxRequestID(c))
} }
func GetGinUserID(c *gin.Context) uint64 { func GetGinUserID(c *gin.Context) xsf.ID {
uid, exists := c.Get(KeyUID) uid, exists := c.Get(KeyUID)
if exists { if exists {
return cast.ToUint64(uid) return xsf.ParseInt64(cast.ToInt64(uid))
} }
return 0 return 0
} }
func GetGinShopID(c *gin.Context) uint64 { func GetGinShopID(c *gin.Context) xsf.ID {
uid, exists := c.Get(KeyShopID) uid, exists := c.Get(KeyShopID)
if exists { if exists {
return cast.ToUint64(uid) return xsf.ParseInt64(cast.ToInt64(uid))
} }
return 0 return 0
} }
func GetCtxUserID(c context.Context) uint64 { func GetCtxUserID(c context.Context) xsf.ID {
uid := c.Value(KeyUID) uid := c.Value(KeyUID)
if uid != nil { if uid != nil {
return cast.ToUint64(uid) return xsf.ParseInt64(cast.ToInt64(uid))
} }
return 0 return 0
} }
func GetCtxShopID(c context.Context) uint64 { func GetCtxShopID(c context.Context) xsf.ID {
uid := c.Value(KeyShopID) uid := c.Value(KeyShopID)
if uid != nil { if uid != nil {
return cast.ToUint64(uid) return xsf.ParseInt64(cast.ToInt64(uid))
} }
return 0 return 0
} }
......
...@@ -7,16 +7,17 @@ import ( ...@@ -7,16 +7,17 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
ctxUtil "gitlab.wanzhuangkj.com/tush/xpkg/gin/xctx"
"gitlab.wanzhuangkj.com/tush/xpkg/logger"
"gitlab.wanzhuangkj.com/tush/xpkg/utils/xjson"
"gitlab.wanzhuangkj.com/tush/xpkg/xerrors/xerror"
"io" "io"
"net/http" "net/http"
"net/url" "net/url"
"strings" "strings"
"time" "time"
ctxUtil "gitlab.wanzhuangkj.com/tush/xpkg/gin/xctx"
"gitlab.wanzhuangkj.com/tush/xpkg/logger"
"gitlab.wanzhuangkj.com/tush/xpkg/utils/xjson"
"gitlab.wanzhuangkj.com/tush/xpkg/xerrors/xerror"
"github.com/duke-git/lancet/v2/retry" "github.com/duke-git/lancet/v2/retry"
) )
...@@ -315,6 +316,9 @@ func (req *Request) send(ctx context.Context, body io.Reader, buf *bytes.Buffer) ...@@ -315,6 +316,9 @@ func (req *Request) send(ctx context.Context, body io.Reader, buf *bytes.Buffer)
logger.Info("http call req", logger.String("req", req.ReqString(ctx)), ctxUtil.CtxTraceIDField(ctx)) logger.Info("http call req", logger.String("req", req.ReqString(ctx)), ctxUtil.CtxTraceIDField(ctx))
var response *http.Response var response *http.Response
response, resp.err = client.Do(req.request) response, resp.err = client.Do(req.request)
if resp.err != nil {
return xerror.New(resp.err.Error())
}
resp.Status = response.Status resp.Status = response.Status
resp.StatusCode = response.StatusCode resp.StatusCode = response.StatusCode
for k, v := range response.Header { for k, v := range response.Header {
......
package xsf
import (
"fmt"
"strconv"
"github.com/bwmarrin/snowflake"
"gitlab.wanzhuangkj.com/tush/xpkg/xerrors/xerror"
)
var node *snowflake.Node
type ID snowflake.ID
func (f ID) MarshalJSON() ([]byte, error) {
buff := make([]byte, 0, 22)
buff = append(buff, '"')
buff = strconv.AppendInt(buff, int64(f), 10)
buff = append(buff, '"')
return buff, nil
}
func (f *ID) UnmarshalJSON(b []byte) error {
if len(b) == 0 {
return nil
}
if len(b) == 1 {
i, err := strconv.ParseInt(string(b), 10, 64)
if err != nil {
return err
}
*f = ID(i)
return nil
}
if len(b) == 2 {
if b[0] == '"' && b[1] == '"' {
*f = ID(0)
}
i, err := strconv.ParseInt(string(b), 10, 64)
if err != nil {
return err
}
*f = ID(i)
return nil
}
if b[0] == '"' && b[len(b)-1] == '"' {
i, err := strconv.ParseInt(string(b[1:len(b)-1]), 10, 64)
if err != nil {
return err
}
*f = ID(i)
return nil
}
i, err := strconv.ParseInt(string(b), 10, 64)
if err != nil {
return err
}
*f = ID(i)
return nil
}
type JSONSyntaxError struct{ original []byte }
func (j JSONSyntaxError) Error() string {
return fmt.Sprintf("invalid xsf ID %q", string(j.original))
}
// n [1,1023]
func Init(n int64) (err error) {
node, err = snowflake.NewNode(n)
if err != nil {
return err
}
return nil
}
func Generate() ID {
return ID(node.Generate())
}
func (x ID) String() string {
return snowflake.ID(x).String()
}
func (x ID) ToInt64() int64 {
return snowflake.ID(x).Int64()
}
func GenerateID() ID {
sid := Generate()
return ID(sid)
}
func ParseInt64(val int64) ID {
return ID(snowflake.ParseInt64(val))
}
func ParseString(val string) (ID, error) {
v, err := snowflake.ParseString(val)
if err != nil {
return 0, xerror.New(err.Error())
}
return ID(v), nil
}
package xsf
import (
"reflect"
"testing"
)
func TestID_MarshalJSON(t *testing.T) {
tests := []struct {
name string
f ID
want []byte
wantErr bool
}{
// TODO: Add test cases.
{
name: "test1",
f: ID(1002),
want: []byte(`"1002"`),
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := tt.f.MarshalJSON()
if (err != nil) != tt.wantErr {
t.Errorf("ID.MarshalJSON() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("ID.MarshalJSON() = %v, want %v", got, tt.want)
}
})
}
}
...@@ -2,12 +2,13 @@ package xslice ...@@ -2,12 +2,13 @@ package xslice
import ( import (
"fmt" "fmt"
"gitlab.wanzhuangkj.com/tush/xpkg/xerrors/xerror"
"gitlab.wanzhuangkj.com/tush/xpkg/xset"
"strings" "strings"
"github.com/jinzhu/copier" "github.com/jinzhu/copier"
"github.com/spf13/cast" "github.com/spf13/cast"
"gitlab.wanzhuangkj.com/tush/xpkg/utils/xsf"
"gitlab.wanzhuangkj.com/tush/xpkg/xerrors/xerror"
"gitlab.wanzhuangkj.com/tush/xpkg/xset"
) )
// connector 连接符 // connector 连接符
...@@ -48,31 +49,31 @@ func StrToUint64(rs []string) []uint64 { ...@@ -48,31 +49,31 @@ func StrToUint64(rs []string) []uint64 {
} }
type IID interface { type IID interface {
GetID() uint64 GetID() xsf.ID
} }
type IIDTable interface { type IIDTable interface {
GetID() uint64 GetID() xsf.ID
TableName() string TableName() string
} }
type ITable interface { type ITable interface {
TableName() uint64 TableName() string
} }
func GetIDs[T IID](rs []*T) []uint64 { func GetIDs[T IID](rs []*T) []xsf.ID {
if len(rs) == 0 { if len(rs) == 0 {
return nil return nil
} }
set := xset.NewSet[uint64]() set := xset.NewSet[xsf.ID]()
for _, r := range rs { for _, r := range rs {
set.Add((*r).GetID()) set.Add((*r).GetID())
} }
return set.ToList() return set.ToList()
} }
func SliceToIDMap[T IID](rs []*T) map[uint64]*T { func SliceToIDMap[T IID](rs []*T) map[xsf.ID]*T {
m := make(map[uint64]*T) m := make(map[xsf.ID]*T)
for _, r := range rs { for _, r := range rs {
m[(*r).GetID()] = r m[(*r).GetID()] = r
} }
...@@ -169,15 +170,15 @@ func StrMapToSlice[T any](m map[string]*T) []*T { ...@@ -169,15 +170,15 @@ func StrMapToSlice[T any](m map[string]*T) []*T {
return rs return rs
} }
func GetStrMapIDs[T IID](m map[string]*T) []uint64 { func GetStrMapIDs[T IID](m map[string]*T) []xsf.ID {
st := xset.NewSet[uint64]() st := xset.NewSet[xsf.ID]()
for _, v := range m { for _, v := range m {
st.Add((*v).GetID()) st.Add((*v).GetID())
} }
return st.ToList() return st.ToList()
} }
func IDMapToSlice[T any](m map[uint64]*T) []*T { func IDMapToSlice[T any](m map[xsf.ID]*T) []*T {
var rs []*T var rs []*T
for _, r := range m { for _, r := range m {
rs = append(rs, r) rs = append(rs, r)
...@@ -185,8 +186,8 @@ func IDMapToSlice[T any](m map[uint64]*T) []*T { ...@@ -185,8 +186,8 @@ func IDMapToSlice[T any](m map[uint64]*T) []*T {
return rs return rs
} }
func GetIDMapIDs[T IID](m map[uint64]*T) []uint64 { func GetIDMapIDs[T IID](m map[xsf.ID]*T) []xsf.ID {
st := xset.NewSet[uint64]() st := xset.NewSet[xsf.ID]()
for _, v := range m { for _, v := range m {
st.Add((*v).GetID()) st.Add((*v).GetID())
} }
...@@ -201,8 +202,8 @@ func StrMapSliceToSlice[T any](m map[string][]*T) []*T { ...@@ -201,8 +202,8 @@ func StrMapSliceToSlice[T any](m map[string][]*T) []*T {
return rs return rs
} }
func GetStrMapSliceIDs[T IID](m map[string][]*T) []uint64 { func GetStrMapSliceIDs[T IID](m map[string][]*T) []xsf.ID {
st := xset.NewSet[uint64]() st := xset.NewSet[xsf.ID]()
for _, rs := range m { for _, rs := range m {
for _, r := range rs { for _, r := range rs {
st.Add((*r).GetID()) st.Add((*r).GetID())
...@@ -211,7 +212,7 @@ func GetStrMapSliceIDs[T IID](m map[string][]*T) []uint64 { ...@@ -211,7 +212,7 @@ func GetStrMapSliceIDs[T IID](m map[string][]*T) []uint64 {
return st.ToList() return st.ToList()
} }
func IDMapSliceToSlice[T any](m map[uint64][]*T) []*T { func IDMapSliceToSlice[T any](m map[xsf.ID][]*T) []*T {
var rs []*T var rs []*T
for _, r := range m { for _, r := range m {
rs = append(rs, r...) rs = append(rs, r...)
...@@ -219,8 +220,8 @@ func IDMapSliceToSlice[T any](m map[uint64][]*T) []*T { ...@@ -219,8 +220,8 @@ func IDMapSliceToSlice[T any](m map[uint64][]*T) []*T {
return rs return rs
} }
func GetIDMapSliceIDs[T IID](m map[uint64][]*T) []uint64 { func GetIDMapSliceIDs[T IID](m map[xsf.ID][]*T) []xsf.ID {
st := xset.NewSet[uint64]() st := xset.NewSet[xsf.ID]()
for _, rs := range m { for _, rs := range m {
for _, r := range rs { for _, r := range rs {
st.Add((*r).GetID()) st.Add((*r).GetID())
...@@ -229,7 +230,7 @@ func GetIDMapSliceIDs[T IID](m map[uint64][]*T) []uint64 { ...@@ -229,7 +230,7 @@ func GetIDMapSliceIDs[T IID](m map[uint64][]*T) []uint64 {
return st.ToList() return st.ToList()
} }
func CompareSlice[T IIDTable, BizSlice ~[]*T](ids []uint64, bizSlice BizSlice, errCode int) error { func CompareSlice[T IIDTable, BizSlice ~[]*T](ids []xsf.ID, bizSlice BizSlice, errCode int) error {
if len(ids) == 0 { if len(ids) == 0 {
return nil return nil
} }
......
package xsf
import (
"github.com/bwmarrin/snowflake"
)
var node *snowflake.Node
// n [1,1023]
func Init(n int64) (err error) {
node, err = snowflake.NewNode(n)
if err != nil {
return err
}
return nil
}
func Generate() snowflake.ID {
return node.Generate()
}
func GenerateID() uint64 {
sid := Generate()
return uint64(sid.Int64())
}
...@@ -3,17 +3,18 @@ package ws ...@@ -3,17 +3,18 @@ package ws
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"net/http"
"sync"
"time"
ctxUtil "gitlab.wanzhuangkj.com/tush/xpkg/gin/xctx" ctxUtil "gitlab.wanzhuangkj.com/tush/xpkg/gin/xctx"
"gitlab.wanzhuangkj.com/tush/xpkg/jwt" "gitlab.wanzhuangkj.com/tush/xpkg/jwt"
"gitlab.wanzhuangkj.com/tush/xpkg/logger" "gitlab.wanzhuangkj.com/tush/xpkg/logger"
"gitlab.wanzhuangkj.com/tush/xpkg/utils/xsf"
"gitlab.wanzhuangkj.com/tush/xpkg/xerrors/xerror" "gitlab.wanzhuangkj.com/tush/xpkg/xerrors/xerror"
"net/http"
"sync"
"time"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/gorilla/websocket" "github.com/gorilla/websocket"
"github.com/spf13/cast"
"go.uber.org/zap" "go.uber.org/zap"
) )
...@@ -27,7 +28,7 @@ const ( ...@@ -27,7 +28,7 @@ const (
type wsConn struct { type wsConn struct {
manager *WsConnManager manager *WsConnManager
id uint64 id xsf.ID
conn *websocket.Conn conn *websocket.Conn
sendBuff chan []byte sendBuff chan []byte
log *zap.Logger log *zap.Logger
...@@ -35,7 +36,7 @@ type wsConn struct { ...@@ -35,7 +36,7 @@ type wsConn struct {
} }
type WsConnManager struct { type WsConnManager struct {
pool map[uint64]*wsConn pool map[xsf.ID]*wsConn
upgrader *websocket.Upgrader upgrader *websocket.Upgrader
sync.RWMutex sync.RWMutex
log *zap.Logger log *zap.Logger
...@@ -47,14 +48,14 @@ var ( ...@@ -47,14 +48,14 @@ var (
) )
type Hook interface { type Hook interface {
AfterSend(ctx context.Context, receiverID uint64, payload *WsMessage) error AfterSend(ctx context.Context, receiverID xsf.ID, payload *WsMessage) error
AfterAccept(ctx context.Context, userID uint64) error AfterAccept(ctx context.Context, userID xsf.ID) error
AfterUnregister(ctx context.Context, userID uint64) error AfterUnregister(ctx context.Context, userID xsf.ID) error
} }
func NewWsConnManager(logger *zap.Logger, upgrader *websocket.Upgrader, hooks ...Hook) *WsConnManager { func NewWsConnManager(logger *zap.Logger, upgrader *websocket.Upgrader, hooks ...Hook) *WsConnManager {
return &WsConnManager{ return &WsConnManager{
pool: make(map[uint64]*wsConn), pool: make(map[xsf.ID]*wsConn),
log: logger, upgrader: upgrader, hooks: hooks} log: logger, upgrader: upgrader, hooks: hooks}
} }
...@@ -107,7 +108,7 @@ func (m *WsConnManager) accept(c *gin.Context) error { ...@@ -107,7 +108,7 @@ func (m *WsConnManager) accept(c *gin.Context) error {
return xerror.Wrap(err, "parse jwt") return xerror.Wrap(err, "parse jwt")
} }
userIDStr := claims.UID userIDStr := claims.UID
userID := cast.ToUint64(userIDStr) userID, _ := xsf.ParseString(userIDStr)
conn, err := m.upgrader.Upgrade(w, r, nil) conn, err := m.upgrader.Upgrade(w, r, nil)
if err != nil { if err != nil {
return xerror.Wrap(err, "ws upgrade failed") return xerror.Wrap(err, "ws upgrade failed")
...@@ -136,14 +137,14 @@ func (m *WsConnManager) accept(c *gin.Context) error { ...@@ -136,14 +137,14 @@ func (m *WsConnManager) accept(c *gin.Context) error {
return nil return nil
} }
func (m *WsConnManager) getConn(userID uint64) (*wsConn, bool) { func (m *WsConnManager) getConn(userID xsf.ID) (*wsConn, bool) {
m.RLock() m.RLock()
defer m.RUnlock() defer m.RUnlock()
client, exists := m.pool[userID] client, exists := m.pool[userID]
return client, exists return client, exists
} }
func (m *WsConnManager) Send(ctx context.Context, receiverID uint64, payload *WsMessage) error { func (m *WsConnManager) Send(ctx context.Context, receiverID xsf.ID, payload *WsMessage) error {
if payload == nil { if payload == nil {
return nil return nil
} }
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论