This repository has been archived by the owner on Aug 22, 2022. It is now read-only.
forked from asciimoo/filtron
-
Notifications
You must be signed in to change notification settings - Fork 6
/
proxy.go
82 lines (67 loc) · 1.66 KB
/
proxy.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
package proxy
import (
"log"
"net/http"
"os"
"github.com/valyala/fasthttp"
"github.com/searxng/filtron/rule"
"github.com/searxng/filtron/types"
)
var transport *http.Transport = &http.Transport{
DisableKeepAlives: false,
}
type Proxy struct {
NumberOfRequests uint
Rules *[]*rule.Rule
client *fasthttp.HostClient
}
func Listen(address, target string, readBufferSize int, rules *[]*rule.Rule) *Proxy {
p := &Proxy{
NumberOfRequests: 0,
Rules: rules,
client: &fasthttp.HostClient{Addr: target, ReadBufferSize: readBufferSize},
}
go func(address string, p *Proxy) {
log.Println("Proxy listens on", address)
fasthttp.ListenAndServe(address, p.Handler)
}(address, p)
return p
}
func (p *Proxy) Handler(ctx *fasthttp.RequestCtx) {
respState := rule.Evaluate(p.Rules, ctx)
if respState == types.SERVED {
return
}
appRequest := fasthttp.AcquireRequest()
defer fasthttp.ReleaseRequest(appRequest)
appRequest.Header.SetMethodBytes(ctx.Method())
ctx.Request.Header.CopyTo(&appRequest.Header)
if ctx.IsPost() || ctx.IsPut() {
appRequest.SetBody(ctx.PostBody())
}
resp := fasthttp.AcquireResponse()
defer fasthttp.ReleaseResponse(resp)
err := p.client.Do(appRequest, resp)
if err != nil {
log.Println("Response error:", err, resp)
ctx.SetStatusCode(429)
return
}
resp.Header.CopyTo(&ctx.Response.Header)
ctx.SetStatusCode(resp.StatusCode())
resp.BodyWriteTo(ctx)
}
func (p *Proxy) ReloadRules(filename string) error {
rules, err := rule.ParseJSONFile(filename)
if err != nil {
return err
}
p.Rules = &rules
return nil
}
func fatal(err error) {
if err != nil {
log.Fatal(err)
os.Exit(1)
}
}