Add newlines to the JSON stream functions

This makes the JSON streams a _lot_ easier to parse in less well-baked JSON parsers, and no less so in better ones.

Line-based JSON streams are very, very common, where simply chunk-based is not very common at all.

Docker-DCO-1.1-Signed-off-by: Andrew Page <admwiggin@gmail.com> (github: tianon)
This commit is contained in:
Tianon Gravi 2014-02-20 23:42:31 -07:00
parent a5515d27e5
commit 060da572d2
1 changed files with 10 additions and 6 deletions

View File

@ -14,6 +14,10 @@ func NewStreamFormatter(json bool) *StreamFormatter {
return &StreamFormatter{json, false}
}
const streamNewline = "\r\n"
var streamNewlineBytes = []byte(streamNewline)
func (sf *StreamFormatter) FormatStream(str string) []byte {
sf.used = true
if sf.json {
@ -21,7 +25,7 @@ func (sf *StreamFormatter) FormatStream(str string) []byte {
if err != nil {
return sf.FormatError(err)
}
return b
return append(b, streamNewlineBytes...)
}
return []byte(str + "\r")
}
@ -34,9 +38,9 @@ func (sf *StreamFormatter) FormatStatus(id, format string, a ...interface{}) []b
if err != nil {
return sf.FormatError(err)
}
return b
return append(b, streamNewlineBytes...)
}
return []byte(str + "\r\n")
return []byte(str + streamNewline)
}
func (sf *StreamFormatter) FormatError(err error) []byte {
@ -47,11 +51,11 @@ func (sf *StreamFormatter) FormatError(err error) []byte {
jsonError = &JSONError{Message: err.Error()}
}
if b, err := json.Marshal(&JSONMessage{Error: jsonError, ErrorMessage: err.Error()}); err == nil {
return b
return append(b, streamNewlineBytes...)
}
return []byte("{\"error\":\"format error\"}")
return []byte("{\"error\":\"format error\"}" + streamNewline)
}
return []byte("Error: " + err.Error() + "\r\n")
return []byte("Error: " + err.Error() + streamNewline)
}
func (sf *StreamFormatter) FormatProgress(id, action string, progress *JSONProgress) []byte {