Skip to content

Commit

Permalink
Merge pull request moby#1394 from crosbymichael/1391-json-requests
Browse files Browse the repository at this point in the history
Use mime pkg to parse Content-Type
  • Loading branch information
Victor Vieux committed Aug 6, 2013
2 parents b6c4b32 + 754ed90 commit 0dbc51f
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 2 deletions.
11 changes: 10 additions & 1 deletion api.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"io"
"io/ioutil"
"log"
"mime"
"net"
"net/http"
"os"
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
}
Expand Down
14 changes: 14 additions & 0 deletions api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit 0dbc51f

Please sign in to comment.