Skip to content

Commit

Permalink
use http.StatusOK as initial value for responseLogger.status (#103)
Browse files Browse the repository at this point in the history
  • Loading branch information
damoye authored and elithrar committed May 23, 2017
1 parent 13d7309 commit a4043c6
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
8 changes: 2 additions & 6 deletions handlers.go
Expand Up @@ -79,9 +79,9 @@ func (h combinedLoggingHandler) ServeHTTP(w http.ResponseWriter, req *http.Reque
}

func makeLogger(w http.ResponseWriter) loggingResponseWriter {
var logger loggingResponseWriter = &responseLogger{w: w}
var logger loggingResponseWriter = &responseLogger{w: w, status: http.StatusOK}
if _, ok := w.(http.Hijacker); ok {
logger = &hijackLogger{responseLogger{w: w}}
logger = &hijackLogger{responseLogger{w: w, status: http.StatusOK}}
}
h, ok1 := logger.(http.Hijacker)
c, ok2 := w.(http.CloseNotifier)
Expand Down Expand Up @@ -114,10 +114,6 @@ func (l *responseLogger) Header() http.Header {
}

func (l *responseLogger) Write(b []byte) (int, error) {
if l.status == 0 {
// The status will be StatusOK if WriteHeader has not been called yet
l.status = http.StatusOK
}
size, err := l.w.Write(b)
l.size += size
return size, err
Expand Down
24 changes: 24 additions & 0 deletions handlers_test.go
Expand Up @@ -73,6 +73,30 @@ func TestMethodHandler(t *testing.T) {
}
}

func TestMakeLogger(t *testing.T) {
rec := httptest.NewRecorder()
logger := makeLogger(rec)
// initial status
if logger.Status() != http.StatusOK {
t.Fatalf("wrong status, got %d want %d", logger.Status(), http.StatusOK)
}
// WriteHeader
logger.WriteHeader(http.StatusInternalServerError)
if logger.Status() != http.StatusInternalServerError {
t.Fatalf("wrong status, got %d want %d", logger.Status(), http.StatusInternalServerError)
}
// Write
logger.Write([]byte(ok))
if logger.Size() != len(ok) {
t.Fatalf("wrong size, got %d want %d", logger.Size(), len(ok))
}
// Header
logger.Header().Set("key", "value")
if val := logger.Header().Get("key"); val != "value" {
t.Fatalf("wrong header, got %s want %s", val, "value")
}
}

func TestWriteLog(t *testing.T) {
loc, err := time.LoadLocation("Europe/Warsaw")
if err != nil {
Expand Down

0 comments on commit a4043c6

Please sign in to comment.