/
main.go
77 lines (63 loc) · 1.56 KB
/
main.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
package main
import (
"./atc"
"flag"
"fmt"
"github.com/elazarl/goproxy"
"log"
"net/http"
)
func isFailure(status int) bool {
return status > 499 || status == -1
}
type responseStatus struct {
host string
status int
length int64
}
type requestStatus struct {
host string
}
func main() {
verbose := flag.Bool("v", false, "should every proxy request be logged to stdout")
addr := flag.String("addr", ":8080", "proxy listen address")
flag.Parse()
proxy := goproxy.NewProxyHttpServer()
proxy.Verbose = *verbose
atc := atc.NewAirTrafficControl()
responses := make(chan responseStatus)
go func() {
for {
msg := <-responses
fmt.Println("respons host", msg.host, "status", msg.status, "len", msg.length)
if isFailure(msg.status) {
atc.ReportFailure(msg.host)
} else {
atc.ReportSuccess(msg.host)
}
}
}()
proxy.OnRequest().DoFunc(
func(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
cleared := atc.GetClearance(r.Host)
if !cleared {
fmt.Println("NOT CLEARED!")
return r, goproxy.NewResponse(r,
goproxy.ContentTypeText, http.StatusGatewayTimeout,
"circuit broken")
}
return r, nil
})
proxy.OnResponse().DoFunc(
func(r *http.Response, ctx *goproxy.ProxyCtx) *http.Response {
if r != nil {
responses <- responseStatus{r.Request.Host, r.StatusCode, r.ContentLength}
} else {
fmt.Println("response ERROR:", ctx.Error)
responses <- responseStatus{ctx.Req.Host, -1, -1}
}
return r
})
fmt.Println("STARTING")
log.Fatal(http.ListenAndServe(*addr, proxy))
}