Skip to content

Commit 0211c88

Browse files
author
Michael Lauer
committed
streamWriter
1 parent 4012178 commit 0211c88

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

streams.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"sync"
77
)
88

9+
// streamReader is really sort of a piper. Maybe
910
type streamReader struct {
1011
buffer bytes.Buffer
1112
lock sync.Mutex
@@ -50,3 +51,35 @@ func (sr *streamReader) Close() error {
5051
sr.gotData.Signal()
5152
return nil
5253
}
54+
55+
// streamWriter writes data as FCGI records.
56+
type streamWriter struct {
57+
w io.Writer
58+
tp recordType
59+
id requestId
60+
lock sync.Mutex
61+
}
62+
63+
func newStreamWriter(w io.Writer, tp recordType, id requestId) *streamWriter {
64+
return &streamWriter{w: w, tp: tp, id: id}
65+
}
66+
67+
func (sw *streamWriter) Write(data []byte) (int, error) {
68+
sw.lock.Lock()
69+
defer sw.lock.Unlock()
70+
if len(data) == 0 {
71+
return 0, nil
72+
}
73+
rec := record{sw.tp, sw.id, data}
74+
err := writeRecord(sw.w, rec)
75+
// How much did we actually write? Just say nothing if we got an error.
76+
if err != nil {
77+
return 0, err
78+
}
79+
return len(data), nil
80+
}
81+
82+
func (sw *streamWriter) Close() error {
83+
// Close means writing an empty string
84+
return writeRecord(sw.w, record{sw.tp, sw.id, nil})
85+
}

streams_test.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package gofcgisrv
22

33
import (
4+
"bytes"
45
"io"
56
"io/ioutil"
67
"strings"
@@ -49,3 +50,22 @@ func TestStreamReader(t *testing.T) {
4950
t.Errorf("Read %s with error %v", read, err)
5051
}
5152
}
53+
54+
func TestStreamWriter(t *testing.T) {
55+
var buffer bytes.Buffer
56+
sw := newStreamWriter(&buffer, fcgiStdout, 3)
57+
io.WriteString(sw, "Foo!")
58+
io.WriteString(sw, "This is data")
59+
io.WriteString(sw, "\000\001abc")
60+
sw.Close()
61+
62+
expected := "\001\006\000\003\000\004\004\000Foo!\000\000\000\000" +
63+
"\001\006\000\003\000\x0c\004\000This is data\000\000\000\000" +
64+
"\001\006\000\003\000\x05\003\000\000\001abc\000\000\000" +
65+
"\001\006\000\003\000\x00\000\000"
66+
67+
str := string(buffer.Bytes())
68+
if str != expected {
69+
t.Errorf("Got\n%q\nnot\n%q", str, expected)
70+
}
71+
}

0 commit comments

Comments
 (0)