-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.go
104 lines (81 loc) · 2.04 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package bytetrap
import (
"net/http"
"strings"
"time"
"fmt"
"log"
)
// int in bytes
var statsCh chan int64
// stolen from https://yourbasic.org/golang/formatting-byte-size-to-human-readable-format/
func ByteCountSI(b int64) string {
const unit = 1000
if b < unit {
return fmt.Sprintf("%d B", b)
}
div, exp := int64(unit), 0
for n := b / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f %cB",
float64(b)/float64(div), "kMGTPE"[exp])
}
func startStats() {
ticker := time.NewTicker(time.Second * 10)
statsCh = make(chan int64)
var total, i, alltime int64
starttime := time.Now()
for {
select {
case i = <-statsCh:
total += i
case <-ticker.C:
if total != 0 {
dur := int64(time.Now().Sub(starttime).Seconds())
alltime += total
log.Printf("[bytetrap/stats] sent %s (%d) bytes in the last 10s (%s over %ds -> %sbit/s)",
ByteCountSI(total), total,
ByteCountSI(alltime), dur,
ByteCountSI(alltime/dur*8),
)
total = 0
}
}
}
}
const BytespiderUA = "Bytespider"
var bytespiderUA = strings.ToLower(BytespiderUA)
// checks if useragent contains BytespiderUA
func IsBytespider(useragent string) bool {
// simple and effective
return strings.Contains(strings.ToLower(useragent), bytespiderUA)
}
// see github.com/gorilla/mux#MiddlewareFunc
type MiddlewareFunc func(http.Handler) http.Handler
type middleware struct {
handler http.Handler
}
func (m *middleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if IsBytespider(r.UserAgent()) {
Write(w)
return
}
m.handler.ServeHTTP(w, r)
}
// sends all `Bytespider`-UAs unlimited copypasta
func Middleware(next http.Handler) http.Handler {
return &middleware{next}
}
var taghtml = TagHTML
// spams copypasta as response
func Handler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
w.Write([]byte("<meta charset=\"UTF-8\">"))
write(w,
true, // do log
[]Tag{TagText, TagHTML}, // only plaintext and html
&taghtml, // convert to html
)
}