Switch LogOf from panicking when logger is missing to creating logger with the defaults.

Update CORS tests to a table-based test and cover more cases.
This commit is contained in:
Jessica Forrester
2014-09-09 17:05:18 -04:00
parent becf6ca4e7
commit 0cac1c5f79
7 changed files with 85 additions and 92 deletions

View File

@@ -86,22 +86,17 @@ func NewLogged(req *http.Request, w *http.ResponseWriter) *respLogger {
return rl
}
// LogOf returns the logger hiding in w. Panics if there isn't such a logger,
// because NewLogged() must have been previously called for the log to work.
func LogOf(w http.ResponseWriter) *respLogger {
// LogOf returns the logger hiding in w. If there is not an existing logger
// then one will be created because NewLogged() must have been previously
// called for the log to work.
func LogOf(req *http.Request, w http.ResponseWriter) *respLogger {
if _, exists := w.(*respLogger); !exists {
NewLogged(req, &w)
}
if rl, ok := w.(*respLogger); ok {
return rl
}
panic("Logger not installed yet!")
}
// Returns the existing logger hiding in w. If there is not an existing logger
// then one will be created.
func FindOrCreateLogOf(req *http.Request, w *http.ResponseWriter) *respLogger {
if _, exists := (*w).(*respLogger); !exists {
NewLogged(req, w)
}
return LogOf(*w)
panic("Unable to find or create the logger!")
}
// Unlogged returns the original ResponseWriter, or w if it is not our inserted logger.

View File

@@ -91,19 +91,12 @@ func TestLogOf(t *testing.T) {
t.Errorf("Unexpected error: %v", err)
}
handler := func(w http.ResponseWriter, r *http.Request) {
var want *respLogger
if makeLogger {
want = NewLogged(req, &w)
} else {
defer func() {
if r := recover(); r == nil {
t.Errorf("Expected LogOf to panic")
}
}()
NewLogged(req, &w)
}
got := LogOf(w)
if want != got {
t.Errorf("Expected %v, got %v", want, got)
got := reflect.TypeOf(*LogOf(r, w)).String()
if got != "httplog.respLogger" {
t.Errorf("Expected %v, got %v", "httplog.respLogger", got)
}
}
w := httptest.NewRecorder()