-
Notifications
You must be signed in to change notification settings - Fork 78
/
Copy pathmain.go
73 lines (64 loc) · 1.92 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package main
import (
"context"
"errors"
"net"
"os"
"os/signal"
"syscall"
"time"
"github.com/charmbracelet/log"
"github.com/charmbracelet/ssh"
"github.com/charmbracelet/wish"
"github.com/charmbracelet/wish/logging"
)
const (
host = "localhost"
port = "23234"
)
func main() {
srv, err := wish.NewServer(
wish.WithAddress(net.JoinHostPort(host, port)),
wish.WithHostKeyPath(".ssh/id_ed25519"),
wish.WithMiddleware(
func(next ssh.Handler) ssh.Handler {
return func(sess ssh.Session) {
wish.Println(sess, "Hello, world!")
next(sess)
}
},
logging.Middleware(),
),
)
if err != nil {
log.Error("Could not start server", "error", err)
}
// Before starting our server, we create a channel and listen for some
// common interrupt signals.
done := make(chan os.Signal, 1)
signal.Notify(done, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
// We then start the server in a goroutine, as we'll listen for the done
// signal later.
go func() {
log.Info("Starting SSH server", "host", host, "port", port)
if err = srv.ListenAndServe(); err != nil && !errors.Is(err, ssh.ErrServerClosed) {
// We ignore ErrServerClosed because it is expected.
log.Error("Could not start server", "error", err)
done <- nil
}
}()
// Here we wait for the done signal: this can be either an interrupt, or
// the server shutting down for any other reason.
<-done
// When it arrives, we create a context with a timeout.
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer func() { cancel() }()
// When we start the shutdown, the server will no longer accept new
// connections, but will wait as much as the given context allows for the
// active connections to finish.
// After the timeout, it shuts down anyway.
log.Info("Stopping SSH server")
if err := srv.Shutdown(ctx); err != nil && !errors.Is(err, ssh.ErrServerClosed) {
log.Error("Could not stop server", "error", err)
}
}