Browse Source

返回格式修改

shao 6 days ago
parent
commit
d660c48e59
3 changed files with 50 additions and 6 deletions
  1. 12 2
      common/rescode.go
  2. 37 3
      common/response.go
  3. 1 1
      rpc_idl

+ 12 - 2
common/rescode.go

@@ -121,7 +121,17 @@ func (p *ResStatus) Translator(localizer *i18n.Localizer) *ResStatus {
 
 func (p *ResStatus) H(data ...interface{}) gin.H {
 	if len(data) > 0 {
-		return gin.H{"status": helper(p.Code, p.Description), "data": data[0]}
+		return gin.H{
+			"code":        p.Code,
+			"description": p.Description,
+			"solution":    p.Solution,
+			"data":        data[0],
+		}
+	}
+	return gin.H{
+		"code":        p.Code,
+		"description": p.Description,
+		"solution":    p.Solution,
+		"data":        gin.H{},
 	}
-	return gin.H{"status": helper(p.Code, p.Description), "data": gin.H{}}
 }

+ 37 - 3
common/response.go

@@ -4,6 +4,7 @@ import (
 	"encoding/json"
 	"errors"
 	"fmt"
+	"log"
 	"log/slog"
 	"net/http"
 	"reflect"
@@ -11,17 +12,50 @@ import (
 )
 
 import (
+	"github.com/gin-gonic/gin"
+	"github.com/go-playground/validator/v10"
+	"google.golang.org/protobuf/encoding/protojson"
+	"google.golang.org/protobuf/proto"
+	"google.golang.org/protobuf/types/known/anypb"
 	"gorm.io/gorm"
 )
 
 import (
-	"github.com/gin-gonic/gin"
-	"github.com/go-playground/validator/v10"
+	"auth-server/rpc_idl/dr_basic_pb"
 )
 
 func HttpSuccess(c *gin.Context, data ...interface{}) {
 	if len(data) > 0 {
-		c.JSON(http.StatusOK, OK.Translator(GetTrans(c.GetHeader("Language"))).H(data[0]))
+		if m, ok := data[0].(proto.Message); ok {
+			success := OK.Translator(GetTrans(c.GetHeader("Language")))
+
+			data, _ := anypb.New(m)
+			resp := dr_basic_pb.HttpResponse{
+				Code:        success.Code,
+				Description: string(success.Description),
+				Solution:    success.Solution,
+				Data:        data,
+			}
+			fullMarshalOptions := protojson.MarshalOptions{
+				EmitUnpopulated: true,
+				UseProtoNames:   true,
+				UseEnumNumbers:  false,
+				Indent:          "",
+			}
+			fullJSON, err := fullMarshalOptions.Marshal(&resp)
+			if err != nil {
+				log.Fatalf("Failed to marshal with EmitUnpopulated: %v", err)
+			}
+			c.Status(http.StatusOK)
+			c.Header("Content-Type", "application/json; charset=utf-8")
+			c.Writer.WriteHeaderNow()
+			if _, err := c.Writer.Write(fullJSON); err != nil {
+				_ = c.Error(err)
+				c.Abort()
+			}
+		} else {
+			c.JSON(http.StatusOK, OK.Translator(GetTrans(c.GetHeader("Language"))).H(data[0]))
+		}
 	} else {
 		c.JSON(http.StatusOK, OK.H())
 	}

+ 1 - 1
rpc_idl

@@ -1 +1 @@
-Subproject commit fd1299aaac1e201fdd1a946f14143d93f04e4c14
+Subproject commit 49438186d81c30b889da5fde0d42ca0a45fbc0d3