summaryrefslogtreecommitdiff
path: root/floodstop.go
blob: ad4af0f60ed08c14d559e36f007c8e40febf1ef5 (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
43
44
45
46
47
package main

import (
	"time"
)

type Floodstop struct {
	ask  chan chan bool
	stop chan struct{}
}

func NewFloodstop(reset time.Duration, countMax int) (fs *Floodstop) {
	fs = &Floodstop{
		ask:  make(chan chan bool),
		stop: make(chan struct{}),
	}

	ticker := time.NewTicker(reset)
	counter := 0

	go func() {
		defer ticker.Stop()
		for {
			select {
			case <-fs.stop:
				return
			case retCh := <-fs.ask:
				counter++
				retCh <- (counter < countMax)
			case <-ticker.C:
				counter = 0
			}
		}
	}()

	return
}

func (fs *Floodstop) Stop() {
	fs.stop <- struct{}{}
}

func (fs *Floodstop) Ask() bool {
	ch := make(chan bool)
	fs.ask <- ch
	return <-ch
}