From 462d142a4cf103bad84f2d578860f7ba51087717 Mon Sep 17 00:00:00 2001 From: gjs Date: Sat, 5 Sep 2026 13:41:13 +0800 Subject: [PATCH] =?UTF-8?q?=E5=9B=9E=E8=B0=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bff/internal/request/user.go | 68 +++---- bff/internal/response/middleware.go | 22 ++- bff/internal/response/response.go | 7 + pkg/utils/loginInfo.go | 26 +-- pkg/utils/tools.go | 13 +- rpc/express/express.pb | Bin 15956 -> 15919 bytes rpc/express/express.proto | 1 - rpc/express/pb/express.pb.go | 13 +- .../internal/logic/expressSfBackLogic.go | 187 +++++++++++++++++- 9 files changed, 254 insertions(+), 83 deletions(-) diff --git a/bff/internal/request/user.go b/bff/internal/request/user.go index 7f1892e..a49a48a 100644 --- a/bff/internal/request/user.go +++ b/bff/internal/request/user.go @@ -1,7 +1,6 @@ package request import ( - "bytes" "context" "io" "lone-services/pkg/utils" @@ -17,24 +16,22 @@ import ( type ctxKey string const ( - CtxUserId ctxKey = "X-User-Id" - CtxUserName ctxKey = "X-User-Name" - CtxRefresh ctxKey = "X-Refresh" - CtxClientIP ctxKey = "X-Client-Ip" - CtxUserAgent ctxKey = "X-User-Agent" - CtxClientCode ctxKey = "X-Client-Code" - CtxSaleId ctxKey = "X-Sale-Id" - CtxSaleName ctxKey = "X-Sale-Name" - CtxSaleMobile ctxKey = "X-Sale-Mobile" - CtxSaleProvince ctxKey = "X-Sale-Province" - CtxStoreId ctxKey = "X-Store-Id" - CtxStoreName ctxKey = "X-Store-Name" - CtxGroupId ctxKey = "X-Group-Id" - CtxGroupName ctxKey = "X-Group-Name" - CtxUserType ctxKey = "X-User-Type" - CtxCallbackRawBody ctxKey = "callback_raw_body" - CtxCallbackHeaders ctxKey = "callback_headers" - CtxCallbackErr ctxKey = "callback_read_err" + CtxUserId ctxKey = "X-User-Id" + CtxUserName ctxKey = "X-User-Name" + CtxRefresh ctxKey = "X-Refresh" + CtxClientIP ctxKey = "X-Client-Ip" + CtxUserAgent ctxKey = "X-User-Agent" + CtxClientCode ctxKey = "X-Client-Code" + CtxSaleId ctxKey = "X-Sale-Id" + CtxSaleName ctxKey = "X-Sale-Name" + CtxSaleMobile ctxKey = "X-Sale-Mobile" + CtxSaleProvince ctxKey = "X-Sale-Province" + CtxStoreId ctxKey = "X-Store-Id" + CtxStoreName ctxKey = "X-Store-Name" + CtxGroupId ctxKey = "X-Group-Id" + CtxGroupName ctxKey = "X-Group-Name" + CtxUserType ctxKey = "X-User-Type" + CtxRawBody ctxKey = "X-Raw-Body" ) var callbackPrefixes = []string{ @@ -60,6 +57,7 @@ type UserInfo struct { StoreName string GroupId string GroupName string + RawBody string Valid bool } @@ -79,6 +77,7 @@ func GetUserInfo(ctx context.Context) UserInfo { storeName, _ := ctx.Value(CtxStoreName).(string) groupId, _ := ctx.Value(CtxGroupId).(string) groupName, _ := ctx.Value(CtxGroupName).(string) + rawBody, _ := ctx.Value(CtxRawBody).(string) info := UserInfo{ RawUID: rawUID, @@ -96,6 +95,7 @@ func GetUserInfo(ctx context.Context) UserInfo { StoreName: storeName, GroupId: groupId, GroupName: groupName, + RawBody: rawBody, } if rawUID == "" { return info @@ -122,29 +122,17 @@ func getRealClientIP(r *http.Request) string { return r.RemoteAddr } +// UserReadMiddleware +/** 增加透传的方法 + * 1、这里加上代码 + * 2、UserClientInterceptor这个方法里也要写相应的代码对可以 + */ func UserReadMiddleware(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - newCtx := r.Context() - if isCallbackPath(r.URL.Path) { - body, err := io.ReadAll(r.Body) - if err != nil { - newCtx = context.WithValue(newCtx, CtxCallbackRawBody, []byte(nil)) - newCtx = context.WithValue(newCtx, CtxCallbackHeaders, http.Header(nil)) - newCtx = context.WithValue(newCtx, CtxCallbackErr, err) - } else { - r.Body = io.NopCloser(bytes.NewBuffer(body)) - header := make(http.Header) - for k, vv := range r.Header { - header[k] = vv - } - newCtx = context.WithValue(newCtx, CtxCallbackRawBody, body) - newCtx = context.WithValue(newCtx, CtxCallbackHeaders, header) - newCtx = context.WithValue(newCtx, CtxCallbackErr, error(nil)) - } - next(w, r.WithContext(newCtx)) - return - } + newCtx := r.Context() + body, _ := io.ReadAll(r.Body) + newCtx = context.WithValue(newCtx, CtxRawBody, string(body)) newCtx = context.WithValue(newCtx, CtxUserId, r.Header.Get("X-User-Id")) newCtx = context.WithValue(newCtx, CtxUserName, r.Header.Get("X-User-Name")) newCtx = context.WithValue(newCtx, CtxRefresh, r.Header.Get("X-Refresh")) @@ -160,7 +148,6 @@ func UserReadMiddleware(next http.HandlerFunc) http.HandlerFunc { newCtx = context.WithValue(newCtx, CtxStoreName, r.Header.Get("X-Store-Name")) newCtx = context.WithValue(newCtx, CtxGroupId, r.Header.Get("X-Group-Id")) newCtx = context.WithValue(newCtx, CtxGroupName, r.Header.Get("X-Group-Name")) - next(w, r.WithContext(newCtx)) } } @@ -189,6 +176,7 @@ func UserClientInterceptor(ctx context.Context, method string, req, reply any, c md.Set("x-user-name", url.QueryEscape(user.Name)) } + setMDIfNotEmpty(md, "x-raw-body", user.RawBody) setMDIfNotEmpty(md, "x-refresh", user.Refresh) setMDIfNotEmpty(md, "x-client-ip", user.ClientIP) if user.UserAgent != utils.StringEmpty { diff --git a/bff/internal/response/middleware.go b/bff/internal/response/middleware.go index 464f6e0..57bff72 100644 --- a/bff/internal/response/middleware.go +++ b/bff/internal/response/middleware.go @@ -2,6 +2,7 @@ package response import ( "bytes" + "lone-services/pkg/utils" "net/http" "strings" @@ -16,6 +17,11 @@ type bodyWriter struct { buf bytes.Buffer } +type responseDataBack struct { + ReturnCode string `json:"returnCode"` + ReturnMsg string `json:"returnMsg"` +} + type responseData struct { Code int32 `json:"code"` Data any `json:"data"` @@ -48,7 +54,21 @@ func Wrap(next http.HandlerFunc) http.HandlerFunc { return } } - ctrl.OutPut(w, data.Code, unwrapJSONData(data.Data), data.Msg) + if data.Code < utils.NumberOne { + var back responseDataBack + + if err := jsoniter.Unmarshal(raw, &back); err != nil { + ctrl.Fail(w) + return + } + if len(back.ReturnCode) < utils.NumberOne { + ctrl.Fail(w) + return + } + ctrl.OutPutBack(w, back) + } else { + ctrl.OutPut(w, data.Code, unwrapJSONData(data.Data), data.Msg) + } } } diff --git a/bff/internal/response/response.go b/bff/internal/response/response.go index f1ad1be..11b600c 100644 --- a/bff/internal/response/response.go +++ b/bff/internal/response/response.go @@ -53,3 +53,10 @@ func (b *BaseController) OutPut(w http.ResponseWriter, code int32, data any, msg w.WriteHeader(http.StatusOK) _ = jsoniter.NewEncoder(w).Encode(out) } + +func (b *BaseController) OutPutBack(w http.ResponseWriter, back responseDataBack) { + + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(http.StatusOK) + _ = jsoniter.NewEncoder(w).Encode(back) +} diff --git a/pkg/utils/loginInfo.go b/pkg/utils/loginInfo.go index d66e725..492cee5 100644 --- a/pkg/utils/loginInfo.go +++ b/pkg/utils/loginInfo.go @@ -2,7 +2,6 @@ package utils import ( "context" - "net/http" "net/url" "strconv" @@ -10,12 +9,6 @@ import ( "google.golang.org/grpc/metadata" ) -const ( - CtxCallbackRawBody string = "callback_raw_body" - CtxCallbackHeaders string = "callback_headers" - CtxCallbackErr string = "callback_read_err" -) - type UserInfo struct { ID int64 Name string @@ -38,11 +31,6 @@ type UserInfo struct { Valid bool } -type HeaderAndBody struct { - Header http.Header - Body []byte -} - func firstMD(md metadata.MD, keys ...string) string { for _, key := range keys { vals := md.Get(key) @@ -122,13 +110,11 @@ func GetUserFromCtx(ctx context.Context) UserInfo { return userInfo } -// GetHeaderAndBody 只从ctx拿数据,不写http响应,Err交给handler处理 -func GetHeaderAndBody(ctx context.Context) HeaderAndBody { - rawBody, _ := ctx.Value(CtxCallbackRawBody).([]byte) - headers, _ := ctx.Value(CtxCallbackHeaders).(http.Header) - - return HeaderAndBody{ - Header: headers, - Body: rawBody, +// GetBody 只从ctx拿数据,不写http响应,Err交给handler处理 +func GetBody(ctx context.Context) string { + md, ok := metadata.FromIncomingContext(ctx) + if !ok { + return StringEmpty } + return firstMD(md, "x-raw-body") } diff --git a/pkg/utils/tools.go b/pkg/utils/tools.go index 0acd02a..821e373 100644 --- a/pkg/utils/tools.go +++ b/pkg/utils/tools.go @@ -14,6 +14,7 @@ import ( "time" jsoniter "github.com/json-iterator/go" + "github.com/zeromicro/go-zero/core/logx" "github.com/gin-gonic/gin" "github.com/xuri/excelize/v2" @@ -245,7 +246,7 @@ func RoundMoney(amount float64) float64 { func Decrypt(str string) (string, Error) { str, err := Crypto{}.AESDecryptECB(str) if err != nil { - Logger.Error("decrypt str error", str, err) + logx.Error("decrypt str error", str, err) return str, err } @@ -259,7 +260,7 @@ func DecryptMobile(mobile string) string { mobile, err := Decrypt(mobile) if err != nil { - Logger.Error("decrypt mobile error", mobile, err) + logx.Error("decrypt mobile error", mobile, err) return mobile } @@ -488,12 +489,12 @@ func Unique(s []string) []string { func MapToStruct(data map[string]interface{}, target interface{}) error { jsonData, err := jsoniter.Marshal(data) // 将 map 转换为 JSON 字节切片 if err != nil { - Logger.Error("Error marshalling map to JSON:", err) + logx.Error("Error marshalling map to JSON:", err) return err } err = jsoniter.Unmarshal(jsonData, &target) // 将 JSON 字节切片解析到结构体中 if err != nil { - Logger.Error("Error unmarshalling JSON:", err) + logx.Error("Error unmarshalling JSON:", err) return err } @@ -503,14 +504,14 @@ func MapToStruct(data map[string]interface{}, target interface{}) error { func JsonStringToStruct(jsonStr string, v interface{}) bool { // 1. 校验入参:确保v是指针类型(否则json.Unmarshal无法工作) if v == nil { - Logger.Error("传入的结构体指针不能为nil") + logx.Error("传入的结构体指针不能为nil") return false } // 2. 将JSON字符串转为字节数组,执行解析 err := jsoniter.Unmarshal([]byte(jsonStr), v) if err != nil { - Logger.Error("JSON解析失败: ", err, jsonStr) + logx.Error("JSON解析失败: ", err, jsonStr) return false } diff --git a/rpc/express/express.pb b/rpc/express/express.pb index 6ba1f7fbcdca1ae913760846fc96894899756fb6..8b5282a7dae47f9013780e7e0bbc7789f291a6bc 100644 GIT binary patch delta 24 gcmcaov%Y4-V`Iislb;y3G5So-Hu2ef$E1Q20GwnCOaK4? delta 62 zcmZ2qbERg(V`Ikmlb;y3F&0kFHt|svQs&|= utils.NumberZero; i-- { + if cOk := oldMap[v[i].LastMd5]; !cOk { + old = append(old, v[i]) + } + } + item.TransitQuery = utils.StructToJson(old) + w := modelbase.Params{Eq: map[string]string{"id": strconv.Itoa(item.Id)}} + if end[item.OrderSn] { + item.SignTime = utils.Now() + } + _, err = modelObj.Edit(w, &item) + if err != nil { + l.Logger.Error("back set deliver info error ", err) + modelObj.Rollback() + return false + } + } + + if end[item.OrderSn] { + if item.Type == dao.DeliveryTypeOrder { + cli, err := svc.GetRpcClient(l.svcCtx.OrderSvcName) + if err != nil { + modelObj.Rollback() + logx.Errorf("get order err: %v", err) + return false + } + + client := order.NewOrderClient(cli.Conn()) + update := order.UpdateOrderDeliverStatusRequest{ + Id: item.ObjId, + DeliverStatus: int32(item.Status), + SignTime: utils.Now().GoString(), + } + _, err = client.UpdateOrderDeliverStatus(l.ctx, &update) + if err != nil { + modelObj.Rollback() + logx.Errorf("get order err: %v", err) + return false + } + } + } + + } + modelObj.Commit() + + return true + +} + +func (l *ExpressSfBackLogic) getSfMap(items []dao.ExpressQueryItems) map[string]bool { + ret := make(map[string]bool) + for _, item := range items { + ret[item.LastMd5] = true + } + return ret }