-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
61 lines (52 loc) · 1.14 KB
/
server.go
File metadata and controls
61 lines (52 loc) · 1.14 KB
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
package go_httpauth
import "crypto/rand"
import "fmt"
import "sync"
import "time"
type Server struct {
sync.Mutex
AuthFun func(user, realm string) string
opaque string
Realm string
ReaperWaitSeconds, ReapTTLSeconds int
requests map[string]*reqState
}
type reqState struct {
nreq int
sectime int64
}
func newServer(realm string, authfun func(user, realm string) string) *Server {
s := new(Server)
s.Realm = realm
s.opaque = newNonce()
s.AuthFun = authfun
s.requests = map[string]*reqState{}
s.ReaperWaitSeconds = 600
s.ReapTTLSeconds = 3600
go reaper(s)
return s
}
func newNonce() string {
b := make([]byte, 8)
n, e := rand.Read(b)
if n != 8 || e != nil {
panic("rand.Reader failed!")
}
return fmt.Sprintf("%x", b)
}
func reaper(s *Server) {
for {
time.Sleep(time.Duration(s.ReaperWaitSeconds) * time.Second)
do_reap(s)
}
}
func do_reap(s *Server) {
now := time.Now().UnixNano()
s.Lock()
defer s.Unlock()
for k, v := range s.requests {
if v.sectime+int64(s.ReapTTLSeconds) < now {
delete(s.requests, k)
}
}
}