Skip to content

Commit

Permalink
Merge branch 'master' of github.com:ant0ine/go-json-rest
Browse files Browse the repository at this point in the history
  • Loading branch information
ant0ine committed Nov 6, 2016
2 parents af20cdf + ed84d40 commit 709bbe3
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
3 changes: 3 additions & 0 deletions rest/recorder.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ type recorderResponseWriter struct {
// Record the status code.
func (w *recorderResponseWriter) WriteHeader(code int) {
w.ResponseWriter.WriteHeader(code)
if w.wroteHeader {
return
}
w.statusCode = code
w.wroteHeader = true
}
Expand Down
43 changes: 42 additions & 1 deletion rest/recorder_test.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
package rest

import (
"github.com/ant0ine/go-json-rest/rest/test"
"testing"

"github.com/ant0ine/go-json-rest/rest/test"
)

func TestRecorderMiddleware(t *testing.T) {
Expand Down Expand Up @@ -91,3 +92,43 @@ func TestRecorderAndGzipMiddleware(t *testing.T) {
recorded.CodeIs(200)
recorded.ContentTypeIsJson()
}

//Underlying net/http only allows you to set the status code once
func TestRecorderMiddlewareReportsSameStatusCodeAsResponse(t *testing.T) {
api := NewApi()
const firstCode = 400
const secondCode = 500

// a middleware carrying the Env tests
api.Use(MiddlewareSimple(func(handler HandlerFunc) HandlerFunc {
return func(w ResponseWriter, r *Request) {

handler(w, r)

if r.Env["STATUS_CODE"] == nil {
t.Error("STATUS_CODE is nil")
}
statusCode := r.Env["STATUS_CODE"].(int)
if statusCode != firstCode {
t.Errorf("STATUS_CODE = %d expected, got %d", firstCode, statusCode)
}
}
}))

// the middleware to test
api.Use(&RecorderMiddleware{})

// a simple app
api.SetApp(AppSimple(func(w ResponseWriter, r *Request) {
w.WriteHeader(firstCode)
w.WriteHeader(secondCode)
}))

// wrap all
handler := api.MakeHandler()

req := test.MakeSimpleRequest("GET", "http://localhost/", nil)
recorded := test.RunRequest(t, handler, req)
recorded.CodeIs(firstCode)
recorded.ContentTypeIsJson()
}

0 comments on commit 709bbe3

Please sign in to comment.