-
Notifications
You must be signed in to change notification settings - Fork 11
/
middleware.go
59 lines (52 loc) · 1.08 KB
/
middleware.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
package main
import (
"errors"
"sync"
"github.com/charmbracelet/ssh"
"github.com/charmbracelet/wish"
)
// connLimiter limits the number of concurrent connections.
type connLimiter struct {
sync.Mutex
conns int
maxConns int
}
// newConnLimiter returns a new connLimiter.
func newConnLimiter(maxConns int) *connLimiter {
return &connLimiter{
maxConns: maxConns,
}
}
// Add adds a connection to the limiter.
func (u *connLimiter) Add() error {
u.Lock()
defer u.Unlock()
if u.conns >= u.maxConns {
return errors.New("max connections reached")
}
u.conns++
return nil
}
// Remove removes a connection from the limiter.
func (u *connLimiter) Remove() {
u.Lock()
defer u.Unlock()
u.conns--
if u.conns < 0 {
u.conns = 0
}
}
// connLimit is a wish middleware that limits the number of concurrent
// connections.
func connLimit(limiter *connLimiter) wish.Middleware {
return func(sh ssh.Handler) ssh.Handler {
return func(s ssh.Session) {
if err := limiter.Add(); err != nil {
wish.Fatalf(s, "max connections reached\n")
return
}
sh(s)
limiter.Remove()
}
}
}