Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
recover middleware wraps other middlewares and recover from panics
- Loading branch information
1 parent
0e458e4
commit beb5f0c
Showing
2 changed files
with
74 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
package recover | ||
|
||
import ( | ||
"log" | ||
"runtime/debug" | ||
|
||
"github.com/charmbracelet/wish" | ||
"github.com/gliderlabs/ssh" | ||
) | ||
|
||
// Middleware is a wish middleware that recovers from panics and log to stderr. | ||
func Middleware(mw ...wish.Middleware) wish.Middleware { | ||
return MiddlewareWithLogger(nil, mw...) | ||
} | ||
|
||
// MiddlewareWithLogger is a wish middleware that recovers from panics and log to | ||
// the provided logger. | ||
func MiddlewareWithLogger(logger *log.Logger, mw ...wish.Middleware) wish.Middleware { | ||
if logger == nil { | ||
logger = log.Default() | ||
} | ||
h := func(ssh.Session) {} | ||
for _, m := range mw { | ||
h = m(h) | ||
} | ||
return func(sh ssh.Handler) ssh.Handler { | ||
return func(s ssh.Session) { | ||
func() { | ||
defer func() { | ||
if r := recover(); r != nil { | ||
logger.Printf("panic: %v\n%s", r, string(debug.Stack())) | ||
} | ||
}() | ||
h(s) | ||
}() | ||
sh(s) | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
package recover | ||
|
||
import ( | ||
"testing" | ||
|
||
"github.com/charmbracelet/wish/testsession" | ||
"github.com/gliderlabs/ssh" | ||
gossh "golang.org/x/crypto/ssh" | ||
) | ||
|
||
func TestMiddleware(t *testing.T) { | ||
t.Run("recover session", func(t *testing.T) { | ||
_, err := setup(t).Output("") | ||
requireNoError(t, err) | ||
}) | ||
} | ||
|
||
func setup(tb testing.TB) *gossh.Session { | ||
tb.Helper() | ||
return testsession.New(tb, &ssh.Server{ | ||
Handler: Middleware(func(h ssh.Handler) ssh.Handler { | ||
return func(s ssh.Session) { | ||
panic("hello") | ||
} | ||
})(func(s ssh.Session) {}), | ||
}, nil) | ||
} | ||
|
||
func requireNoError(t *testing.T, err error) { | ||
t.Helper() | ||
|
||
if err != nil { | ||
t.Fatalf("expected no error, got %q", err.Error()) | ||
} | ||
} |