Skip to content

Commit

Permalink
Add back old HTTP flushing functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
bobheadxi committed May 28, 2018
1 parent aca0d05 commit cbc18fe
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 7 deletions.
25 changes: 19 additions & 6 deletions daemon/inertiad/log/routine.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package log
import (
"bufio"
"io"
"net/http"
)

// FlushRoutine continuously writes everything in given ReadCloser
Expand All @@ -13,19 +14,31 @@ ROUTINE:
for {
select {
case <-stop:
line, err := reader.ReadBytes('\n')
if err == nil {
w.Write(line)
}
WriteAndFlush(w, reader)
break ROUTINE
default:
// Read from pipe then write to ResponseWriter and flush it,
// sending the copied content to the client.
line, err := reader.ReadBytes('\n')
err := WriteAndFlush(w, reader)
if err != nil {
break ROUTINE
}
w.Write(line)
}
}
}

// WriteAndFlush reads from buffer, writes to writer, and flushes if possible
func WriteAndFlush(w io.Writer, reader *bufio.Reader) error {
line, err := reader.ReadBytes('\n')
if err != nil {
return err
}

// Write to writer, and flush as well if it is a flusher
w.Write(line)
if f, ok := w.(http.Flusher); ok {
f.Flush()
}

return nil
}
49 changes: 48 additions & 1 deletion daemon/inertiad/log/routine_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package log

import (
"bufio"
"fmt"
"io"
"net/http"
Expand All @@ -13,7 +14,7 @@ import (
"github.com/stretchr/testify/assert"
)

func TestFlushRoutine(t *testing.T) {
func TestFlushRoutineWebSocket(t *testing.T) {
testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// establish socket connection
var upgrader = websocket.Upgrader{}
Expand Down Expand Up @@ -82,3 +83,49 @@ func TestFlushRoutine(t *testing.T) {
i++
}
}

func TestFlushRoutineHTTP(t *testing.T) {
testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
reader, writer := io.Pipe()
stop := make(chan struct{})
go FlushRoutine(w, reader, stop)

fmt.Println(writer, "Hello!")
time.Sleep(time.Millisecond)

fmt.Println(writer, "Lunch?")
time.Sleep(time.Millisecond)

fmt.Println(writer, "Bye!")
time.Sleep(time.Millisecond)

close(stop)
fmt.Println(writer, "Do I live?")
}))
defer testServer.Close()

resp, err := http.DefaultClient.Get(testServer.URL)
assert.Nil(t, err)

reader := bufio.NewReader(resp.Body)
i := 0
for i < 4 {
line, err := reader.ReadBytes('\n')
if err != nil {
break
}

switch i {
case 0:
assert.Equal(t, "Hello!", string(line))
case 1:
assert.Equal(t, "Lunch?", string(line))
case 2:
assert.Equal(t, "Bye!", string(line))
case 3:
assert.Equal(t, "", string(line))
}

i++
}
}

0 comments on commit cbc18fe

Please sign in to comment.