yjp 1 éve
szülő
commit
dddef4862d

+ 20 - 12
convenient/domain_gateway/sql_executor.go

@@ -3,6 +3,7 @@ package domain_gateway
 import (
 	"git.sxidc.com/go-framework/baize/framework/core/api"
 	"git.sxidc.com/go-framework/baize/framework/gateway"
+	"git.sxidc.com/go-tools/utils/strutils"
 	"github.com/pkg/errors"
 	"net/http"
 )
@@ -11,20 +12,25 @@ func SqlExecutorGateway(baseUrlNoUrlPrefix string, builder *gateway.Builder) {
 	builder.
 		Url(http.MethodPost, "/sql/execute").
 		Request(func(c *api.Context, historyRequests []gateway.BuilderRequest, resultMap map[string]any) (gateway.BuilderRequest, error) {
-			bodyMap, err := gateway.AddJsonBodyTenantIDAndUserID(c, "", "executorId")
+			err := gateway.AddJsonBodyTenantIDAndUserID(c, "", "executorId")
+			if err != nil {
+				return nil, err
+			}
+
+			jsonBody, err := c.GetJsonBody()
 			if err != nil {
 				return nil, err
 			}
 
 			userInfo := c.GetUserInfo()
 			if userInfo == nil {
-				bodyMap["executorName"] = "guest"
+				jsonBody.Set("executorName", "guest")
 			} else {
-				bodyMap["executorName"] = userInfo.GetName()
+				jsonBody.Set("executorName", userInfo.GetName)
 			}
 
-			urlPrefixValue, ok := bodyMap["urlPrefix"]
-			if !ok {
+			urlPrefixValue := jsonBody.Get("urlPrefix")
+			if urlPrefixValue == nil {
 				return nil, errors.New("没有传递服务名")
 			}
 
@@ -33,11 +39,11 @@ func SqlExecutorGateway(baseUrlNoUrlPrefix string, builder *gateway.Builder) {
 				return nil, errors.New("服务名不是string类型")
 			}
 
-			delete(bodyMap, "urlPrefix")
+			jsonBody.Delete("urlPrefix")
 
 			return &gateway.PostRequest{
 				Url:  baseUrlNoUrlPrefix + "/" + urlPrefix + "/api/sql/execute",
-				Body: bodyMap,
+				Body: jsonBody.Map(),
 			}, nil
 		}, nil).
 		Build()
@@ -45,21 +51,23 @@ func SqlExecutorGateway(baseUrlNoUrlPrefix string, builder *gateway.Builder) {
 	builder.
 		Url(http.MethodGet, "/sql/execute/log").
 		Request(func(c *api.Context, historyRequests []gateway.BuilderRequest, resultMap map[string]any) (gateway.BuilderRequest, error) {
-			queryPrams, err := gateway.AddQueryParamsTenantIDAndUserID(c, "", "executorId")
+			err := gateway.AddQueryParamsTenantIDAndUserID(c, "", "executorId")
 			if err != nil {
 				return nil, err
 			}
 
-			urlPrefix, ok := queryPrams["urlPrefix"]
-			if !ok {
+			queryParams := c.GetQueryParams()
+
+			urlPrefix := queryParams.Get("urlPrefix")
+			if strutils.IsStringEmpty(urlPrefix) {
 				return nil, errors.New("没有传递服务名")
 			}
 
-			delete(queryPrams, "urlPrefix")
+			queryParams.Delete("urlPrefix")
 
 			return &gateway.GetRequest{
 				Url:         baseUrlNoUrlPrefix + "/" + urlPrefix + "/api/sql/execute/log",
-				QueryParams: queryPrams,
+				QueryParams: queryParams.Map(),
 			}, nil
 		}, nil).
 		Build()

+ 16 - 6
convenient/gwtools/entity_crud.go

@@ -70,14 +70,19 @@ func (params *EntityCRUDParams) crud(builder *gateway.Builder) {
 		builder.
 			Url(http.MethodPost, domainPath+"/create").
 			Request(func(c *api.Context, historyRequests []gateway.BuilderRequest, resultMap map[string]any) (gateway.BuilderRequest, error) {
-				newBody, err := gateway.AddJsonBodyTenantIDAndUserID(c, "tenantId", "createUserId")
+				err := gateway.AddJsonBodyTenantIDAndUserID(c, "tenantId", "createUserId")
+				if err != nil {
+					return nil, err
+				}
+
+				jsonBody, err := c.GetJsonBody()
 				if err != nil {
 					return nil, err
 				}
 
 				return &gateway.PostRequest{
 					Url:  params.ServiceVersionedUrl + domainPath + "/create",
-					Body: newBody,
+					Body: jsonBody.Map(),
 				}, nil
 			}, createOptions.requestResponseCallback).
 			Build(createOptions.middlewares...)
@@ -98,14 +103,19 @@ func (params *EntityCRUDParams) crud(builder *gateway.Builder) {
 		builder.
 			Url(http.MethodPut, domainPath+"/update").
 			Request(func(c *api.Context, historyRequests []gateway.BuilderRequest, resultMap map[string]any) (gateway.BuilderRequest, error) {
-				newBody, err := gateway.AddJsonBodyTenantIDAndUserID(c, "", "updateUserId")
+				err := gateway.AddJsonBodyTenantIDAndUserID(c, "", "updateUserId")
+				if err != nil {
+					return nil, err
+				}
+
+				jsonBody, err := c.GetJsonBody()
 				if err != nil {
 					return nil, err
 				}
 
 				return &gateway.PutRequest{
 					Url:  params.ServiceVersionedUrl + domainPath + "/update",
-					Body: newBody,
+					Body: jsonBody.Map(),
 				}, nil
 			}, updateOptions.requestResponseCallback).
 			Build(updateOptions.middlewares...)
@@ -116,14 +126,14 @@ func (params *EntityCRUDParams) crud(builder *gateway.Builder) {
 		builder.
 			Url(http.MethodGet, domainPath+"/query").
 			Request(func(c *api.Context, historyRequests []gateway.BuilderRequest, resultMap map[string]any) (gateway.BuilderRequest, error) {
-				newQueryParams, err := gateway.AddQueryParamsTenantIDAndUserID(c, "tenantId", "")
+				err := gateway.AddQueryParamsTenantIDAndUserID(c, "tenantId", "")
 				if err != nil {
 					return nil, err
 				}
 
 				return &gateway.GetRequest{
 					Url:         params.ServiceVersionedUrl + domainPath + "/query",
-					QueryParams: newQueryParams,
+					QueryParams: c.GetQueryParams().Map(),
 				}, nil
 			}, queryOptions.requestResponseCallback).
 			Build(queryOptions.middlewares...)

+ 2 - 2
convenient/gwtools/one2many.go

@@ -88,14 +88,14 @@ func (params *One2ManyParams) one2many(builder *gateway.Builder) {
 			builder.
 				Url(http.MethodGet, rightDomainPath+leftDomainPath+"/queryWith").
 				Request(func(c *api.Context, historyRequests []gateway.BuilderRequest, resultMap map[string]any) (gateway.BuilderRequest, error) {
-					newQueryParams, err := gateway.AddQueryParamsTenantIDAndUserID(c, "tenantId", "")
+					err := gateway.AddQueryParamsTenantIDAndUserID(c, "tenantId", "")
 					if err != nil {
 						return nil, err
 					}
 
 					return &gateway.GetRequest{
 						Url:         params.ServiceVersionedUrl + rightDomainPath + leftDomainPath + "/queryWith",
-						QueryParams: newQueryParams,
+						QueryParams: c.GetQueryParams().Map(),
 					}, nil
 				}, nil).
 				Build()

+ 4 - 4
convenient/gwtools/one2one.go

@@ -66,14 +66,14 @@ func (params *One2OneParams) one2one(builder *gateway.Builder) {
 			builder.
 				Url(http.MethodGet, leftDomainPath+rightDomainPath+"/queryWith").
 				Request(func(c *api.Context, historyRequests []gateway.BuilderRequest, resultMap map[string]any) (gateway.BuilderRequest, error) {
-					newQueryParams, err := gateway.AddQueryParamsTenantIDAndUserID(c, "tenantId", "")
+					err := gateway.AddQueryParamsTenantIDAndUserID(c, "tenantId", "")
 					if err != nil {
 						return nil, err
 					}
 
 					return &gateway.GetRequest{
 						Url:         params.ServiceVersionedUrl + leftDomainPath + rightDomainPath + "/queryWith",
-						QueryParams: newQueryParams,
+						QueryParams: c.GetQueryParams().Map(),
 					}, nil
 				}, nil).
 				Build()
@@ -106,14 +106,14 @@ func (params *One2OneParams) one2one(builder *gateway.Builder) {
 			builder.
 				Url(http.MethodGet, rightDomainPath+leftDomainPath+"/queryWith").
 				Request(func(c *api.Context, historyRequests []gateway.BuilderRequest, resultMap map[string]any) (gateway.BuilderRequest, error) {
-					newQueryParams, err := gateway.AddQueryParamsTenantIDAndUserID(c, "tenantId", "")
+					err := gateway.AddQueryParamsTenantIDAndUserID(c, "tenantId", "")
 					if err != nil {
 						return nil, err
 					}
 
 					return &gateway.GetRequest{
 						Url:         params.ServiceVersionedUrl + rightDomainPath + leftDomainPath + "/queryWith",
-						QueryParams: newQueryParams,
+						QueryParams: c.GetQueryParams().Map(),
 					}, nil
 				}, nil).
 				Build()

+ 9 - 4
convenient/gwtools/value_object_crud.go

@@ -58,14 +58,19 @@ func (params *ValueObjectCRUDParams) crud(builder *gateway.Builder) {
 		builder.
 			Url(http.MethodPost, domainPath+"/create").
 			Request(func(c *api.Context, historyRequests []gateway.BuilderRequest, resultMap map[string]any) (gateway.BuilderRequest, error) {
-				newBody, err := gateway.AddJsonBodyTenantIDAndUserID(c, "tenantId", "createUserId")
+				err := gateway.AddJsonBodyTenantIDAndUserID(c, "tenantId", "createUserId")
+				if err != nil {
+					return nil, err
+				}
+
+				jsonBody, err := c.GetJsonBody()
 				if err != nil {
 					return nil, err
 				}
 
 				return &gateway.PostRequest{
 					Url:  params.ServiceVersionedUrl + domainPath + "/create",
-					Body: newBody,
+					Body: jsonBody.Map(),
 				}, nil
 			}, createOptions.requestResponseCallback).
 			Build(createOptions.middlewares...)
@@ -86,14 +91,14 @@ func (params *ValueObjectCRUDParams) crud(builder *gateway.Builder) {
 		builder.
 			Url(http.MethodGet, domainPath+"/query").
 			Request(func(c *api.Context, historyRequests []gateway.BuilderRequest, resultMap map[string]any) (gateway.BuilderRequest, error) {
-				newQueryParams, err := gateway.AddQueryParamsTenantIDAndUserID(c, "tenantId", "")
+				err := gateway.AddQueryParamsTenantIDAndUserID(c, "tenantId", "")
 				if err != nil {
 					return nil, err
 				}
 
 				return &gateway.GetRequest{
 					Url:         params.ServiceVersionedUrl + domainPath + "/query",
-					QueryParams: newQueryParams,
+					QueryParams: c.GetQueryParams().Map(),
 				}, nil
 			}, queryOptions.requestResponseCallback).
 			Build(queryOptions.middlewares...)

+ 181 - 32
framework/core/api/context.go

@@ -11,6 +11,12 @@ import (
 	"strings"
 )
 
+const (
+	bodyKey        = "body-context"
+	queryParamsKey = "query-params-context"
+	pathParamsKey  = "path-params-context"
+)
+
 type Context struct {
 	*gin.Context
 }
@@ -48,61 +54,179 @@ func (c *Context) GetHeaders() map[string]string {
 	return headers
 }
 
-func (c *Context) ReadBody() ([]byte, error) {
-	if c.Request.Body == nil {
-		return make([]byte, 0), nil
+type CacheBody struct {
+	c         *Context
+	bytesBody []byte
+}
+
+func (cacheBody *CacheBody) Set(bytesBody []byte) {
+	cacheBody.bytesBody = bytesBody
+	cacheBody.c.Set(bodyKey, cacheBody.bytesBody)
+}
+
+func (cacheBody *CacheBody) Bytes() []byte {
+	return cacheBody.bytesBody
+}
+
+func (c *Context) GetBytesBody() (*CacheBody, error) {
+	body, exist := c.Get(bodyKey)
+	if !exist {
+		bytesBody, err := c.readOriginBody()
+		if err != nil {
+			return nil, err
+		}
+
+		return &CacheBody{
+			c:         c,
+			bytesBody: bytesBody,
+		}, nil
 	}
 
-	body, err := io.ReadAll(c.Request.Body)
+	return &CacheBody{
+		c:         c,
+		bytesBody: body.([]byte),
+	}, nil
+}
+
+type JsonBody struct {
+	c           *Context
+	jsonBodyMap map[string]any
+}
+
+func (jsonBody *JsonBody) Set(key string, value any) {
+	jsonBody.jsonBodyMap[key] = value
+	jsonBody.c.Set(bodyKey, jsonBody.jsonBodyMap)
+}
+
+func (jsonBody *JsonBody) Delete(key string) {
+	delete(jsonBody.jsonBodyMap, key)
+	jsonBody.c.Set(bodyKey, jsonBody.jsonBodyMap)
+}
+
+func (jsonBody *JsonBody) Get(key string) any {
+	return jsonBody.jsonBodyMap[key]
+}
+
+func (jsonBody *JsonBody) Map() map[string]any {
+	return jsonBody.jsonBodyMap
+}
+
+func (jsonBody *JsonBody) Bytes() ([]byte, error) {
+	return json.Marshal(jsonBody.jsonBodyMap)
+}
+
+func (jsonBody *JsonBody) Unmarshal(output any) error {
+	jsonBytes, err := jsonBody.Bytes()
 	if err != nil {
-		return nil, errors.New(err.Error())
+		return err
 	}
 
-	defer func(Body io.ReadCloser) {
-		err := Body.Close()
+	return json.Unmarshal(jsonBytes, output)
+}
+
+func (c *Context) GetJsonBody() (*JsonBody, error) {
+	body, exist := c.Get(bodyKey)
+	if !exist {
+		bytesBody, err := c.readOriginBody()
 		if err != nil {
-			logger.GetInstance().Error(errors.New(err.Error()))
-			return
+			return nil, err
 		}
-	}(c.Request.Body)
 
-	c.Request.Body = io.NopCloser(bytes.NewBuffer(body))
+		jsonBodyMap := make(map[string]any)
+		err = json.Unmarshal(bytesBody, &jsonBodyMap)
+		if err != nil {
+			return nil, err
+		}
 
-	return body, nil
+		return &JsonBody{
+			c:           c,
+			jsonBodyMap: jsonBodyMap,
+		}, nil
+	}
+
+	return &JsonBody{
+		c:           c,
+		jsonBodyMap: body.(map[string]any),
+	}, nil
 }
 
-func (c *Context) ReplaceBody(body []byte) error {
-	if c.Request.Body != nil {
-		err := c.Request.Body.Close()
-		if err != nil {
-			return errors.New(err.Error())
+type QueryPrams struct {
+	c           *Context
+	queryParams map[string]string
+}
+
+func (queryParams *QueryPrams) Set(key string, value string) {
+	queryParams.queryParams[key] = value
+	queryParams.c.Set(queryParamsKey, queryParams.queryParams)
+}
+
+func (queryParams *QueryPrams) Delete(key string) {
+	delete(queryParams.queryParams, key)
+	queryParams.c.Set(queryParamsKey, queryParams.queryParams)
+}
+
+func (queryParams *QueryPrams) Get(key string) string {
+	return queryParams.queryParams[key]
+}
+
+func (queryParams *QueryPrams) Map() map[string]string {
+	return queryParams.queryParams
+}
+
+func (c *Context) GetQueryParams() *QueryPrams {
+	queryParams, exist := c.Get(queryParamsKey)
+	if !exist {
+		return &QueryPrams{
+			c:           c,
+			queryParams: c.getAllQueryParams(),
 		}
 	}
 
-	c.Request.Body = io.NopCloser(bytes.NewBuffer(body))
+	return &QueryPrams{
+		c:           c,
+		queryParams: queryParams.(map[string]string),
+	}
+}
 
-	return nil
+type PathPrams struct {
+	c          *Context
+	pathParams map[string]string
 }
 
-func (c *Context) ReadJsonBody(output any) error {
-	body, err := c.ReadBody()
-	if err != nil {
-		return err
-	}
+func (pathParams *PathPrams) Set(key string, value string) {
+	pathParams.pathParams[key] = value
+	pathParams.c.Set(pathParamsKey, pathParams.pathParams)
+}
 
-	return json.Unmarshal(body, output)
+func (pathParams *PathPrams) Delete(key string) {
+	delete(pathParams.pathParams, key)
+	pathParams.c.Set(pathParamsKey, pathParams.pathParams)
 }
 
-func (c *Context) ReplaceJsonBody(body any) error {
-	bodyBytes, err := json.Marshal(body)
-	if err != nil {
-		return errors.New(err.Error())
+func (pathParams *PathPrams) Get(key string) string {
+	return pathParams.pathParams[key]
+}
+
+func (pathParams *PathPrams) Map() map[string]string {
+	return pathParams.pathParams
+}
+
+func (c *Context) GetPathParams() *PathPrams {
+	pathParams, exist := c.Get(pathParamsKey)
+	if !exist {
+		return &PathPrams{
+			c:          c,
+			pathParams: c.getAllPathParams(),
+		}
 	}
 
-	return c.ReplaceBody(bodyBytes)
+	return &PathPrams{
+		c:          c,
+		pathParams: pathParams.(map[string]string),
+	}
 }
 
-func (c *Context) GetAllQueryParams() map[string]string {
+func (c *Context) getAllQueryParams() map[string]string {
 	queryParams := make(map[string]string, 0)
 
 	for key, values := range c.Request.URL.Query() {
@@ -112,7 +236,7 @@ func (c *Context) GetAllQueryParams() map[string]string {
 	return queryParams
 }
 
-func (c *Context) GetAllPathParams() map[string]string {
+func (c *Context) getAllPathParams() map[string]string {
 	pathParams := make(map[string]string, 0)
 
 	for _, params := range c.Params {
@@ -122,6 +246,31 @@ func (c *Context) GetAllPathParams() map[string]string {
 	return pathParams
 }
 
+func (c *Context) readOriginBody() ([]byte, error) {
+	if c.Request.Body == nil {
+		return make([]byte, 0), nil
+	}
+
+	body, err := io.ReadAll(c.Request.Body)
+	if err != nil {
+		return nil, errors.New(err.Error())
+	}
+
+	defer func(Body io.ReadCloser) {
+		err := Body.Close()
+		if err != nil {
+			logger.GetInstance().Error(errors.New(err.Error()))
+			return
+		}
+	}(c.Request.Body)
+
+	c.Request.Body = io.NopCloser(bytes.NewBuffer(body))
+
+	c.Set(bodyKey, body)
+
+	return body, nil
+}
+
 const (
 	tenantInfoKey = "context-tenant-info"
 	userInfoKey   = "context-user-info"

+ 6 - 6
framework/gateway/builder.go

@@ -42,7 +42,7 @@ func (builder *Builder) Url(httpMethod string, relativePath string) *Builder {
 func (builder *Builder) Post(request *PostRequest, requestCallbackFunc RequestResponseCallback) *Builder {
 	return builder.Request(func(c *api.Context, historyRequests []BuilderRequest, resultMap map[string]any) (BuilderRequest, error) {
 		if request.Body == nil {
-			body, err := c.ReadBody()
+			body, err := c.GetBytesBody()
 			if err != nil {
 				return nil, err
 			}
@@ -61,11 +61,11 @@ func (builder *Builder) Post(request *PostRequest, requestCallbackFunc RequestRe
 func (builder *Builder) Delete(request *DeleteRequest, requestCallbackFunc RequestResponseCallback) *Builder {
 	return builder.Request(func(c *api.Context, historyRequests []BuilderRequest, resultMap map[string]any) (BuilderRequest, error) {
 		if request.PathParams == nil {
-			request.PathParams = c.GetAllPathParams()
+			request.PathParams = c.GetPathParams().Map()
 		}
 
 		if request.QueryParams == nil {
-			request.QueryParams = c.GetAllQueryParams()
+			request.QueryParams = c.GetQueryParams().Map()
 		}
 
 		return &DeleteRequest{
@@ -80,7 +80,7 @@ func (builder *Builder) Delete(request *DeleteRequest, requestCallbackFunc Reque
 func (builder *Builder) Put(request *PutRequest, requestCallbackFunc RequestResponseCallback) *Builder {
 	return builder.Request(func(c *api.Context, historyRequests []BuilderRequest, resultMap map[string]any) (BuilderRequest, error) {
 		if request.Body == nil {
-			body, err := c.ReadBody()
+			body, err := c.GetBytesBody()
 			if err != nil {
 				return nil, err
 			}
@@ -99,11 +99,11 @@ func (builder *Builder) Put(request *PutRequest, requestCallbackFunc RequestResp
 func (builder *Builder) Get(request *GetRequest, requestCallbackFunc RequestResponseCallback) *Builder {
 	return builder.Request(func(c *api.Context, historyRequests []BuilderRequest, resultMap map[string]any) (BuilderRequest, error) {
 		if request.PathParams == nil {
-			request.PathParams = c.GetAllPathParams()
+			request.PathParams = c.GetPathParams().Map()
 		}
 
 		if request.QueryParams == nil {
-			request.QueryParams = c.GetAllQueryParams()
+			request.QueryParams = c.GetQueryParams().Map()
 		}
 
 		return &GetRequest{

+ 21 - 27
framework/gateway/common.go

@@ -5,59 +5,53 @@ import (
 	"git.sxidc.com/go-tools/utils/strutils"
 )
 
-func AddJsonBodyTenantIDAndUserID(c *api.Context, tenantIDField string, userIDField string) (map[string]any, error) {
-	bodyMap := make(map[string]any)
-	err := c.ReadJsonBody(&bodyMap)
+func AddJsonBodyTenantIDAndUserID(c *api.Context, tenantIDField string, userIDField string) error {
+	jsonBody, err := c.GetJsonBody()
 	if err != nil {
-		return nil, err
+		return err
 	}
 
-	_, ok := bodyMap[tenantIDField]
-	if !ok {
+	tenantID := jsonBody.Get(tenantIDField)
+	if tenantID == nil {
 		tenantInfo := c.GetTenantInfo()
 
 		if tenantInfo != nil {
-			bodyMap[tenantIDField] = tenantInfo.GetID()
+			jsonBody.Set(tenantIDField, tenantInfo.GetID())
 		} else {
-			bodyMap[tenantIDField] = "guest-" + strutils.SimpleUUID()[:26]
+			jsonBody.Set(tenantIDField, "guest-"+strutils.SimpleUUID()[:26])
 		}
 	}
 
-	_, ok = bodyMap[userIDField]
-	if !ok {
+	userID := jsonBody.Get(userIDField)
+	if userID == nil {
 		userInfo := c.GetUserInfo()
 
 		if userInfo != nil {
-			bodyMap[userIDField] = userInfo.GetID()
+			jsonBody.Set(userIDField, userInfo.GetID())
 		} else {
-			bodyMap[userIDField] = "guest-" + strutils.SimpleUUID()[:26]
+			jsonBody.Set(userIDField, "guest-"+strutils.SimpleUUID()[:26])
 		}
 	}
 
-	err = c.ReplaceJsonBody(bodyMap)
-	if err != nil {
-		return nil, err
-	}
-
-	return bodyMap, nil
+	return nil
 }
 
-func AddQueryParamsTenantIDAndUserID(c *api.Context, tenantIDField string, userIDField string) (map[string]string, error) {
-	queryParams := c.GetAllQueryParams()
+func AddQueryParamsTenantIDAndUserID(c *api.Context, tenantIDField string, userIDField string) error {
+	queryParams := c.GetQueryParams()
 
 	if c.GetTenantInfo() != nil {
-		_, ok := queryParams[tenantIDField]
-		if !ok {
-			queryParams[tenantIDField] = c.GetTenantInfo().GetID()
+		tenantID := queryParams.Get(tenantIDField)
+		if strutils.IsStringEmpty(tenantID) {
+			queryParams.Set(tenantIDField, c.GetTenantInfo().GetID())
 		}
 	}
 
 	if c.GetUserInfo() != nil {
-		_, ok := queryParams[userIDField]
-		if !ok {
-			queryParams[userIDField] = c.GetUserInfo().GetID()
+		userID := queryParams.Get(userIDField)
+		if strutils.IsStringEmpty(userID) {
+			queryParams.Set(userIDField, c.GetUserInfo().GetID())
 		}
 	}
 
-	return queryParams, nil
+	return nil
 }