From 288848a9381280e60ddc04bbd70416cac42bd804 Mon Sep 17 00:00:00 2001 From: n9te9 <53435330+lkeix@users.noreply.github.com> Date: Sat, 16 Nov 2024 05:50:55 +0900 Subject: [PATCH] Improve transport.Post Do method (#3373) * optimize: type convertions * optimize: graphql raw params * fmt --- graphql/handler/transport/http_post.go | 34 ++++++++++++++++++++------ 1 file changed, 26 insertions(+), 8 deletions(-) diff --git a/graphql/handler/transport/http_post.go b/graphql/handler/transport/http_post.go index 985f8db2941..4b9a2399eff 100644 --- a/graphql/handler/transport/http_post.go +++ b/graphql/handler/transport/http_post.go @@ -1,11 +1,12 @@ package transport import ( + "bytes" "fmt" "io" "mime" "net/http" - "strings" + "sync" "github.com/vektah/gqlparser/v2/gqlerror" @@ -46,32 +47,49 @@ func getRequestBody(r *http.Request) (string, error) { return string(body), nil } +var pool = sync.Pool{ + New: func() any { + return &graphql.RawParams{} + }, +} + func (h POST) Do(w http.ResponseWriter, r *http.Request, exec graphql.GraphExecutor) { ctx := r.Context() writeHeaders(w, h.ResponseHeaders) - params := &graphql.RawParams{} - start := graphql.Now() + params := pool.Get().(*graphql.RawParams) + defer func() { + params.Headers = nil + params.ReadTime = graphql.TraceTiming{} + params.Extensions = nil + params.OperationName = "" + params.Query = "" + params.Variables = nil + + pool.Put(params) + }() params.Headers = r.Header + + start := graphql.Now() params.ReadTime = graphql.TraceTiming{ Start: start, End: graphql.Now(), } - bodyString, err := getRequestBody(r) + bodyBytes, err := io.ReadAll(r.Body) if err != nil { - gqlErr := gqlerror.Errorf("could not get json request body: %+v", err) + gqlErr := gqlerror.Errorf("could not read request body: %+v", err) resp := exec.DispatchError(ctx, gqlerror.List{gqlErr}) writeJson(w, resp) return } - bodyReader := io.NopCloser(strings.NewReader(bodyString)) - if err = jsonDecode(bodyReader, ¶ms); err != nil { + bodyReader := bytes.NewReader(bodyBytes) + if err := jsonDecode(bodyReader, ¶ms); err != nil { w.WriteHeader(http.StatusBadRequest) gqlErr := gqlerror.Errorf( "json request body could not be decoded: %+v body:%s", err, - bodyString, + string(bodyBytes), ) resp := exec.DispatchError(ctx, gqlerror.List{gqlErr}) writeJson(w, resp)