From 58bf356e7b90b587ec6edc75649dfe0533a7b51e Mon Sep 17 00:00:00 2001 From: Anirudh Raja Date: Wed, 28 Feb 2024 14:45:49 +0530 Subject: [PATCH 1/2] Validating json before handing off to handler --- runtime/router/router.go | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/runtime/router/router.go b/runtime/router/router.go index 7eccbef8a..7655dcb24 100644 --- a/runtime/router/router.go +++ b/runtime/router/router.go @@ -21,8 +21,11 @@ package router import ( + "bytes" "context" + "encoding/json" "fmt" + "io/ioutil" "net/http" "sort" "strings" @@ -130,6 +133,23 @@ func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) { if handler, params, err := trie.Get(reqPath, isWhitelisted); err == nil { ctx := context.WithValue(req.Context(), urlParamsKey, params) req = req.WithContext(ctx) + body, err := ioutil.ReadAll(req.Body) + if err != nil { + http.Error(w, "Failed to read request body", http.StatusInternalServerError) + return + } + reqSize := len(body) + if reqSize == 0 { + http.Error(w, "Failed to parse JSON data", http.StatusBadRequest) + return + } + var buf bytes.Buffer + if err := json.Compact(&buf, body); err != nil { + http.Error(w, "Failed to parse JSON data", http.StatusBadRequest) + return + } + //Reset back into req body. + req.Body = ioutil.NopCloser(bytes.NewReader(buf.Bytes())) handler.ServeHTTP(w, req) return } From 2e2b9147e6e7438da36058af1701d9ef00c295e9 Mon Sep 17 00:00:00 2001 From: Anirudh Raja Date: Thu, 29 Feb 2024 12:14:53 +0530 Subject: [PATCH 2/2] Stringifying error responses --- runtime/server_http_response.go | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/runtime/server_http_response.go b/runtime/server_http_response.go index bfd2f2e19..b538700cc 100644 --- a/runtime/server_http_response.go +++ b/runtime/server_http_response.go @@ -36,6 +36,11 @@ import ( "go.uber.org/zap/zapcore" ) +const ( + // _errTmpl is Error Template + _errTmpl = `{"error":%s}` +) + // ServerHTTPResponse struct manages server http response type ServerHTTPResponse struct { Request *ServerHTTPRequest @@ -169,7 +174,7 @@ func (res *ServerHTTPResponse) SendErrorString( statusCode int, errMsg string, ) { res.WriteJSONBytes(statusCode, nil, - []byte(`{"error":"`+errMsg+`"}`), + []byte(populateJSONTemplate(_errTmpl, errMsg)), ) } @@ -179,7 +184,7 @@ func (res *ServerHTTPResponse) SendError( ) { res.Err = errCause res.WriteJSONBytes(statusCode, nil, - []byte(`{"error":"`+errMsg+`"}`), + []byte(populateJSONTemplate(_errTmpl, errMsg)), ) } @@ -337,3 +342,7 @@ func (res *ServerHTTPResponse) GetPendingResponseObject() interface{} { func (res *ServerHTTPResponse) Headers() http.Header { return res.responseWriter.Header() } + +func populateJSONTemplate(template, msg string) string { + return fmt.Sprintf(template, strconv.Quote(msg)) +}