From 754ed9043d6e1fed98160c7fb443bed0a9464acf Mon Sep 17 00:00:00 2001 From: Michael Crosby Date: Sat, 3 Aug 2013 20:55:54 +0000 Subject: [PATCH] Use mime types to parse Content-Type --- api.go | 11 ++++++++++- api_test.go | 14 ++++++++++++++ commands.go | 2 +- 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/api.go b/api.go index f520d7a73b..f5f0df1b98 100644 --- a/api.go +++ b/api.go @@ -9,6 +9,7 @@ import ( "io" "io/ioutil" "log" + "mime" "net" "net/http" "os" @@ -81,6 +82,14 @@ func getBoolParam(value string) (bool, error) { return ret, nil } +func matchesContentType(contentType, expectedType string) bool { + mimetype, _, err := mime.ParseMediaType(contentType) + if err != nil { + utils.Debugf("Error parsing media type: %s error: %s", contentType, err.Error()) + } + return err == nil && mimetype == expectedType +} + func postAuth(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error { authConfig := &auth.AuthConfig{} err := json.NewDecoder(r.Body).Decode(authConfig) @@ -594,7 +603,7 @@ func postContainersStart(srv *Server, version float64, w http.ResponseWriter, r // allow a nil body for backwards compatibility if r.Body != nil { - if r.Header.Get("Content-Type") == "application/json" { + if matchesContentType(r.Header.Get("Content-Type"), "application/json") { if err := json.NewDecoder(r.Body).Decode(hostConfig); err != nil { return err } diff --git a/api_test.go b/api_test.go index be535924b7..5316b4fc5e 100644 --- a/api_test.go +++ b/api_test.go @@ -1142,6 +1142,20 @@ func TestDeleteImages(t *testing.T) { } */ } +func TestJsonContentType(t *testing.T) { + if !matchesContentType("application/json", "application/json") { + t.Fail() + } + + if !matchesContentType("application/json; charset=utf-8", "application/json") { + t.Fail() + } + + if matchesContentType("dockerapplication/json", "application/json") { + t.Fail() + } +} + // Mocked types for tests type NopConn struct { io.ReadCloser diff --git a/commands.go b/commands.go index 78916f3a7c..c52126519a 100644 --- a/commands.go +++ b/commands.go @@ -1567,7 +1567,7 @@ func (cli *DockerCli) stream(method, path string, in io.Reader, out io.Writer) e return fmt.Errorf("Error: %s", body) } - if resp.Header.Get("Content-Type") == "application/json" { + if matchesContentType(resp.Header.Get("Content-Type"), "application/json") { return utils.DisplayJSONMessagesStream(resp.Body, out) } else { if _, err := io.Copy(out, resp.Body); err != nil {