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