package recoverer import ( "io/ioutil" "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestRecoverer(t *testing.T) { logStackFn := func(stack []byte) { s := string(stack) assert.Contains(t, s, "goroutine") assert.Contains(t, s, "TestRecoverer") } logRecoverFn := func(rec interface{}) { s, ok := rec.(string) assert.True(t, ok) assert.Contains(t, s, "panic message") } recoverer := Middleware( SetLogStackFn(logStackFn), SetLogRecoverFn(logRecoverFn), ) handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/panic" { panic("panic message") } w.WriteHeader(http.StatusOK) _, err := w.Write([]byte("resp")) require.NoError(t, err) }) server := httptest.NewServer(recoverer(handler)) defer server.Close() res, err := http.Get(server.URL) assert.NoError(t, err) defer res.Body.Close() assert.Equal(t, http.StatusOK, res.StatusCode) b, err := ioutil.ReadAll(res.Body) assert.NoError(t, err) assert.Equal(t, "resp", string(b)) res, err = http.Get(server.URL + "/panic") assert.NoError(t, err) defer res.Body.Close() assert.Equal(t, http.StatusInternalServerError, res.StatusCode) }