Browse code

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)

Tianon Gravi authored on 2014/02/21 15:42:31
Showing 1 changed files
... ...
@@ -14,6 +14,10 @@ func NewStreamFormatter(json bool) *StreamFormatter {
14 14
 	return &StreamFormatter{json, false}
15 15
 }
16 16
 
17
+const streamNewline = "\r\n"
18
+
19
+var streamNewlineBytes = []byte(streamNewline)
20
+
17 21
 func (sf *StreamFormatter) FormatStream(str string) []byte {
18 22
 	sf.used = true
19 23
 	if sf.json {
... ...
@@ -21,7 +25,7 @@ func (sf *StreamFormatter) FormatStream(str string) []byte {
21 21
 		if err != nil {
22 22
 			return sf.FormatError(err)
23 23
 		}
24
-		return b
24
+		return append(b, streamNewlineBytes...)
25 25
 	}
26 26
 	return []byte(str + "\r")
27 27
 }
... ...
@@ -34,9 +38,9 @@ func (sf *StreamFormatter) FormatStatus(id, format string, a ...interface{}) []b
34 34
 		if err != nil {
35 35
 			return sf.FormatError(err)
36 36
 		}
37
-		return b
37
+		return append(b, streamNewlineBytes...)
38 38
 	}
39
-	return []byte(str + "\r\n")
39
+	return []byte(str + streamNewline)
40 40
 }
41 41
 
42 42
 func (sf *StreamFormatter) FormatError(err error) []byte {
... ...
@@ -47,11 +51,11 @@ func (sf *StreamFormatter) FormatError(err error) []byte {
47 47
 			jsonError = &JSONError{Message: err.Error()}
48 48
 		}
49 49
 		if b, err := json.Marshal(&JSONMessage{Error: jsonError, ErrorMessage: err.Error()}); err == nil {
50
-			return b
50
+			return append(b, streamNewlineBytes...)
51 51
 		}
52
-		return []byte("{\"error\":\"format error\"}")
52
+		return []byte("{\"error\":\"format error\"}" + streamNewline)
53 53
 	}
54
-	return []byte("Error: " + err.Error() + "\r\n")
54
+	return []byte("Error: " + err.Error() + streamNewline)
55 55
 }
56 56
 
57 57
 func (sf *StreamFormatter) FormatProgress(id, action string, progress *JSONProgress) []byte {