소스 검색

新增uri和body的设置

dcsunny 4 년 전
부모
커밋
b2ae165513
3개의 변경된 파일34개의 추가작업 그리고 2개의 파일을 삭제
  1. 10 0
      http/handle.go
  2. 8 2
      http/middleware/rpc_value.go
  3. 16 0
      http/param/base.go

+ 10 - 0
http/handle.go

@@ -2,11 +2,14 @@ package http
 
 import (
 	"bytes"
+	"context"
 	json2 "encoding/json"
 	"io/ioutil"
 	"net/http"
 	"strings"
 
+	context2 "git.ikuban.com/server/kratos-utils/http/context"
+
 	"google.golang.org/grpc/codes"
 	status2 "google.golang.org/grpc/status"
 
@@ -210,3 +213,10 @@ func contentSubtype(contentType string) string {
 		return ""
 	}
 }
+
+func SetBody(ctx context.Context, r *http.Request) {
+	b, _ := ioutil.ReadAll(r.Body)
+	if len(b) > 0 {
+		ctx = context2.AppendToContext(ctx, "body", b)
+	}
+}

+ 8 - 2
http/middleware/rpc_value.go

@@ -37,13 +37,11 @@ func GrpcValue(handler middleware.Handler) middleware.Handler {
 				_page, _ := strconv.ParseInt(page[0], 10, 64)
 				ctx = context2.AppendToContext(ctx, "page", _page)
 			}
-
 			pageSize := md.Get("page_size")
 			if len(pageSize) > 0 {
 				_pageSize, _ := strconv.ParseInt(pageSize[0], 10, 64)
 				ctx = context2.AppendToContext(ctx, "page_size", _pageSize)
 			}
-
 			query := md.Get("query")
 			if len(query) > 0 {
 				_query, _ := url.ParseQuery(query[0])
@@ -53,6 +51,14 @@ func GrpcValue(handler middleware.Handler) middleware.Handler {
 			if len(referer) > 0 {
 				ctx = context2.AppendToContext(ctx, "referer", referer[0])
 			}
+			body := md.Get("body")
+			if len(body) > 0 {
+				ctx = context2.AppendToContext(ctx, "body", []byte(body[0]))
+			}
+			uri := md.Get("uri")
+			if len(uri) > 0 {
+				ctx = context2.AppendToContext(ctx, "uri", uri[0])
+			}
 		}
 		return handler(ctx, req)
 	}

+ 16 - 0
http/param/base.go

@@ -20,3 +20,19 @@ func GetFromPath(c context.Context) string {
 	}
 	return ""
 }
+
+func GetBody(c context.Context) []byte {
+	body := c.Value("body")
+	if _, ok := body.([]byte); ok {
+		return body.([]byte)
+	}
+	return nil
+}
+
+func GetUri(c context.Context) string {
+	uri := c.Value("uri")
+	if _, ok := uri.(string); ok {
+		return uri.(string)
+	}
+	return ""
+}