Commit 55c816ca authored by Kamil Trzcinski's avatar Kamil Trzcinski

More robust application/json matching

parent e837d788
...@@ -58,7 +58,7 @@ func readRunnerBody(w http.ResponseWriter, r *http.Request) ([]byte, error) { ...@@ -58,7 +58,7 @@ func readRunnerBody(w http.ResponseWriter, r *http.Request) ([]byte, error) {
func readRunnerRequest(r *http.Request, body []byte) (runnerRequest, error) { func readRunnerRequest(r *http.Request, body []byte) (runnerRequest, error) {
var runnerRequest runnerRequest var runnerRequest runnerRequest
if r.Header.Get("Content-Type") != "application/json" { if !helper.IsApplicationJson(r) {
return runnerRequest, errors.New("invalid content-type received") return runnerRequest, errors.New("invalid content-type received")
} }
......
...@@ -170,6 +170,11 @@ func IsContentType(expected, actual string) bool { ...@@ -170,6 +170,11 @@ func IsContentType(expected, actual string) bool {
return err == nil && parsed == expected return err == nil && parsed == expected
} }
func IsApplicationJson(r *http.Request) bool {
contentType := r.Header.Get("Content-Type")
return IsContentType("application/json", contentType)
}
func ReadRequestBody(w http.ResponseWriter, r *http.Request, maxBodySize int64) ([]byte, error) { func ReadRequestBody(w http.ResponseWriter, r *http.Request, maxBodySize int64) ([]byte, error) {
limitedBody := http.MaxBytesReader(w, r.Body, maxBodySize) limitedBody := http.MaxBytesReader(w, r.Body, maxBodySize)
defer limitedBody.Close() defer limitedBody.Close()
......
...@@ -101,3 +101,22 @@ func TestCloneRequestWithBody(t *testing.T) { ...@@ -101,3 +101,22 @@ func TestCloneRequestWithBody(t *testing.T) {
t.Fatal("Expected the readed body to be the same as passed to function") t.Fatal("Expected the readed body to be the same as passed to function")
} }
} }
func TestApplicationJson(t *testing.T) {
req := httptest.NewRequest("POST", "/test", nil)
req.Header.Set("Content-Type", "application/json")
if !IsApplicationJson(req) {
t.Fatalf("Expected to match 'application/json' as 'application/json'")
}
req.Header.Set("Content-Type", "application/json; charset=utf-8")
if !IsApplicationJson(req) {
t.Fatalf("Expected to match 'application/json; charset=utf-8' as 'application/json'")
}
req.Header.Set("Content-Type", "text/plain")
if IsApplicationJson(req) {
t.Fatalf("Expected not to match 'text/plain' as 'application/json'")
}
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment