summaryrefslogtreecommitdiff
path: root/rate.go
blob: 0ab03ac479c9d84570d46f517825431cb0a58741 (plain)
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
package main

import (
	"log"
	"sync"
	"time"
)

// TODO rate limiting

type WatchList struct {
	sync.Mutex
	n    int
	d    time.Duration
	list map[string]int
}

func NewWatchList(n int, d time.Duration) WatchList {
	return WatchList{n: n, d: d, list: make(map[string]int)}
}

func (w WatchList) Add(kick chan string, nick string) {
	w.Lock()
	defer w.Unlock()

	if _, ok := w.list[nick]; !ok {
		go func() {
			<-time.After(w.d)
			w.Lock()
			defer w.Unlock()
			log.Println(w.list[nick], "clear", nick)
			delete(w.list, nick)
		}()
	}

	log.Println(w.list[nick], "hit", nick)
	if w.list[nick] > w.n {
		kick <- nick
	}

	w.list[nick]++
}