Skip to content

Commit

Permalink
Merge pull request #138 from melito/master
Browse files Browse the repository at this point in the history
Add Flusher to the ResponseWriter wrapper
  • Loading branch information
codegangsta committed Dec 28, 2013
2 parents d305eda + 063dfcd commit 957bc53
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
8 changes: 8 additions & 0 deletions response_writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
// if the functionality calls for it.
type ResponseWriter interface {
http.ResponseWriter
http.Flusher
// Status returns the status code of the response or 0 if the response has not been written.
Status() int
// Written returns whether or not the ResponseWriter has been written.
Expand Down Expand Up @@ -87,3 +88,10 @@ func (rw *responseWriter) callBefore() {
rw.beforeFuncs[i](rw)
}
}

func (rw *responseWriter) Flush() {
flusher, ok := rw.ResponseWriter.(http.Flusher)
if ok {
flusher.Flush()
}
}
46 changes: 46 additions & 0 deletions response_writer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package martini

import (
"bufio"
"io"
"net"
"net/http"
"net/http/httptest"
Expand Down Expand Up @@ -140,3 +141,48 @@ func Test_ResponseWriter_CloseNotify(t *testing.T) {
}
expect(t, closed, true)
}

func Test_ResponseWriter_Flusher(t *testing.T) {

rec := httptest.NewRecorder()
rw := NewResponseWriter(rec)

_, ok := rw.(http.Flusher)
expect(t, ok, true)
}

func Test_ResponseWriter_FlusherHandler(t *testing.T) {

// New martini instance
m := Classic()

m.Get("/events", func(w http.ResponseWriter, r *http.Request) {

f, ok := w.(http.Flusher)
expect(t, ok, true)

w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")

for i := 0; i < 2; i++ {
time.Sleep(10 * time.Millisecond)
io.WriteString(w, "data: Hello\n\n")
f.Flush()
}

})

recorder := httptest.NewRecorder()
r, _ := http.NewRequest("GET", "/events", nil)
m.ServeHTTP(recorder, r)

if recorder.Code != 200 {
t.Error("Response not 200")
}

if recorder.Body.String() != "data: Hello\n\ndata: Hello\n\n" {
t.Error("Didn't receive correct body, got:", recorder.Body.String())
}

}

0 comments on commit 957bc53

Please sign in to comment.