From 1cdd2419200df64ef9fa6762703bb918fc325361 Mon Sep 17 00:00:00 2001 From: Denis Makogon Date: Sat, 30 Sep 2017 03:17:03 +0300 Subject: [PATCH] Trying to avoid buffers and write directly to pipe this change makes Dispatch write request body and http headers directly to pipe one by one in case of non-empty request body, if not - write headers and close finalize JSON --- api/agent/protocol/json.go | 43 +++++++++++++++++++++++++++++--------- 1 file changed, 33 insertions(+), 10 deletions(-) diff --git a/api/agent/protocol/json.go b/api/agent/protocol/json.go index 0e2bc2f7e..d6adb9e97 100644 --- a/api/agent/protocol/json.go +++ b/api/agent/protocol/json.go @@ -1,7 +1,6 @@ package protocol import ( - "bytes" "encoding/json" "fmt" "io" @@ -27,27 +26,51 @@ func (p *JSONProtocol) IsStreamable() bool { } func (h *JSONProtocol) Dispatch(w io.Writer, req *http.Request) error { - var body bytes.Buffer + _, err := io.WriteString(h.in, `{`) + if err != nil { + // this shouldn't happen + return respondWithError( + w, fmt.Errorf("error reader JSON object from request body: %s", err.Error())) + } if req.Body != nil { - var dest io.Writer = &body - - // TODO copy w/ ctx - _, err := io.Copy(dest, req.Body) + _, err := io.WriteString(h.in, `"body":"`) if err != nil { + // this shouldn't happen + return respondWithError( + w, fmt.Errorf("error reader JSON object from request body: %s", err.Error())) + } + _, err = io.CopyN(h.in, req.Body, req.ContentLength) + if err != nil { + // this shouldn't happen + return respondWithError( + w, fmt.Errorf("error reader JSON object from request body: %s", err.Error())) + } + _, err = io.WriteString(h.in, `",`) + if err != nil { + // this shouldn't happen return respondWithError( w, fmt.Errorf("error reader JSON object from request body: %s", err.Error())) } defer req.Body.Close() } - err := json.NewEncoder(h.in).Encode(&JSONIO{ - Headers: req.Header, - Body: body.String(), - }) + _, err = io.WriteString(h.in, `"headers:"`) + if err != nil { + // this shouldn't happen + return respondWithError( + w, fmt.Errorf("error reader JSON object from request body: %s", err.Error())) + } + err = json.NewEncoder(h.in).Encode(req.Header) if err != nil { // this shouldn't happen return respondWithError( w, fmt.Errorf("error marshalling JSONInput: %s", err.Error())) } + _, err = io.WriteString(h.in, `"}`) + if err != nil { + // this shouldn't happen + return respondWithError( + w, fmt.Errorf("error reader JSON object from request body: %s", err.Error())) + } jout := new(JSONIO) dec := json.NewDecoder(h.out)