Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error string validate json conversion #930

Open
wants to merge 2 commits into
base: version-2
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions runtime/router/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,11 @@
package router

import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"sort"
"strings"
Expand Down Expand Up @@ -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
}
Expand Down
13 changes: 11 additions & 2 deletions runtime/server_http_response.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -169,7 +174,7 @@ func (res *ServerHTTPResponse) SendErrorString(
statusCode int, errMsg string,
) {
res.WriteJSONBytes(statusCode, nil,
[]byte(`{"error":"`+errMsg+`"}`),
[]byte(populateJSONTemplate(_errTmpl, errMsg)),
)
}

Expand All @@ -179,7 +184,7 @@ func (res *ServerHTTPResponse) SendError(
) {
res.Err = errCause
res.WriteJSONBytes(statusCode, nil,
[]byte(`{"error":"`+errMsg+`"}`),
[]byte(populateJSONTemplate(_errTmpl, errMsg)),
)
}

Expand Down Expand Up @@ -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))
}
Loading