Pārlūkot izejas kodu

新增一些reply方法

dcsunny 4 gadi atpakaļ
vecāks
revīzija
e4cf5cb4d4
2 mainītis faili ar 37 papildinājumiem un 7 dzēšanām
  1. 0 7
      common/reply.go
  2. 37 0
      http/reply/reply.go

+ 0 - 7
common/reply.go

@@ -1,7 +0,0 @@
-package common
-
-type SuccessReply struct {
-	Code    int         `json:"code"`
-	Message string      `json:"message"`
-	Data    interface{} `json:"data"`
-}

+ 37 - 0
http/reply/reply.go

@@ -1,7 +1,44 @@
 package reply
 
+import (
+	"encoding/json"
+	"net/http"
+
+	"github.com/go-kratos/kratos/v2/errors"
+	http2 "github.com/go-kratos/kratos/v2/transport/http"
+)
+
 type SuccessReply struct {
 	Code    int32       `json:"code"`
 	Message string      `json:"message"`
 	Data    interface{} `json:"data"`
 }
+
+func SetContentType(w http.ResponseWriter, contentType string) {
+	if contentType == "" {
+		return
+	}
+	w.Header().Set("Content-Type", contentType)
+}
+
+func ErrorReturn(err error, w http.ResponseWriter, r *http.Request, h http2.HandleOptions) {
+	errStatus := errors.FromError(err)
+	if errStatus != nil {
+		if errStatus.Reason != "" {
+			fail := &SuccessReply{
+				Code:    errStatus.GRPCStatus().Proto().Code,
+				Message: errStatus.GRPCStatus().Message(),
+			}
+			var obj interface{}
+			json.Unmarshal([]byte(errors.Reason(err)), &obj)
+			fail.Data = obj
+			w.WriteHeader(400)
+			if err = h.Encode(w, r, fail); err != nil {
+				h.Error(w, r, err)
+			}
+			return
+		}
+	}
+	h.Error(w, r, err)
+	return
+}