diff --git a/commands.go b/commands.go index 01ab8a334f..7a0a5be3ee 100644 --- a/commands.go +++ b/commands.go @@ -1258,14 +1258,9 @@ func (cli *DockerCli) stream(method, path string, in io.Reader, out io.Writer) e } if resp.Header.Get("Content-Type") == "application/json" { - type Message struct { - Status string `json:"status,omitempty"` - Progress string `json:"progress,omitempty"` - Error string `json:"error,omitempty"` - } dec := json.NewDecoder(resp.Body) for { - var m Message + var m utils.JsonMessage if err := dec.Decode(&m); err == io.EOF { break } else if err != nil { diff --git a/server.go b/server.go index 3353796475..6ebf337dd0 100644 --- a/server.go +++ b/server.go @@ -368,7 +368,7 @@ func (srv *Server) pullRepository(out io.Writer, remote, askedTag string, sf *ut success := false for _, ep := range repoData.Endpoints { if err := srv.pullImage(out, img.Id, "https://"+ep+"/v1", repoData.Tokens, sf); err != nil { - fmt.Fprintf(out, sf.FormatStatus("Error while retrieving image for tag: %s (%s); checking next endpoint\n"), askedTag, err) + fmt.Fprintf(out, sf.FormatStatus("Error while retrieving image for tag: %s (%s); checking next endpoint"), askedTag, err) continue } success = true diff --git a/utils/utils.go b/utils/utils.go index ec05c657e3..1fce76e5aa 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -4,6 +4,7 @@ import ( "bytes" "crypto/sha256" "encoding/hex" + "encoding/json" "errors" "fmt" "index/suffixarray" @@ -557,6 +558,12 @@ func NewWriteFlusher(w io.Writer) *WriteFlusher { return &WriteFlusher{w: w, flusher: flusher} } +type JsonMessage struct { + Status string `json:"status,omitempty"` + Progress string `json:"progress,omitempty"` + Error string `json:"error,omitempty"` +} + type StreamFormatter struct { json bool used bool @@ -569,7 +576,11 @@ func NewStreamFormatter(json bool) *StreamFormatter { func (sf *StreamFormatter) FormatStatus(str string) string { sf.used = true if sf.json { - return "{\"status\" : \"" + str + "\"}" + b, err := json.Marshal(&JsonMessage{Status:str}); + if err != nil { + return sf.FormatError(err) + } + return string(b) } return str + "\r\n" } @@ -577,7 +588,10 @@ func (sf *StreamFormatter) FormatStatus(str string) string { func (sf *StreamFormatter) FormatError(err error) string { sf.used = true if sf.json { - return "{\"error\" : \"" + err.Error() + "\"}" + if b, err := json.Marshal(&JsonMessage{Error:err.Error()}); err == nil { + return string(b) + } + return "{\"error\":\"format error\"}" } return "Error: " + err.Error() + "\r\n" } @@ -585,7 +599,11 @@ func (sf *StreamFormatter) FormatError(err error) string { func (sf *StreamFormatter) FormatProgress(action, str string) string { sf.used = true if sf.json { - return "{\"progress\" : \"" + str + "\"}" + b, err := json.Marshal(&JsonMessage{Progress:str}) + if err != nil { + return sf.FormatError(err) + } + return string(b) } return action + " " + str + "\r" }