-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathserver.go
100 lines (83 loc) · 2.37 KB
/
server.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
package main
import (
"fmt"
"log"
"regexp"
"github.com/logrusorgru/aurora"
"github.com/valyala/fasthttp"
)
func getServer(o *options) *fasthttp.Server {
proxyPathPattern := regexp.MustCompile(`^\/` + o.cleanURLSection)
requestHandler := func(ctx *fasthttp.RequestCtx) {
proxyPath := string(ctx.Path())
if proxyPathPattern.MatchString(proxyPath) {
proxyRequestHandler(
ctx,
o,
proxyPathPattern.ReplaceAllString(proxyPath, ``),
)
} else {
ctx.Error("Not found", fasthttp.StatusNotFound)
}
}
server := &fasthttp.Server{
Handler: requestHandler,
}
go func() {
err := server.ListenAndServe(o.addr)
if err != nil {
log.Fatal(err)
} else {
fmt.Println(aurora.Red("Shutted down!\n").Bold())
}
}()
return server
}
func proxyRequestHandler(ctx *fasthttp.RequestCtx, o *options, proxyPath string) {
req := fasthttp.AcquireRequest()
defer fasthttp.ReleaseRequest(req)
res := fasthttp.AcquireResponse()
defer fasthttp.ReleaseResponse(res)
proxiedURI := o.cleanURL + proxyPath
ctx.Request.CopyTo(req)
req.SetRequestURI(proxiedURI)
for headerName, headerValue := range o.parsedHeaders {
req.Header.Set(headerName, headerValue)
}
if err := fasthttp.Do(req, res); err != nil {
ctx.Error(err.Error(), 500)
}
res.Header.Set("Access-Control-Allow-Methods", "GET,HEAD,PUT,PATCH,POST,DELETE")
res.Header.Set("Access-Control-Allow-Credentials", "true")
if o.reflectOrigin {
res.Header.Set("Access-Control-Allow-Origin", string(ctx.Request.Header.Peek("Origin")))
res.Header.Set("Vary", "Origin")
} else if o.origin != "" {
res.Header.Set("Access-Control-Allow-Origin", o.origin)
res.Header.Set("Vary", "Origin")
} else {
res.Header.Set("Access-Control-Allow-Origin", "*")
res.Header.Set("Vary", "*")
}
if ctx.IsOptions() {
accessControlRequestHeaders := string(ctx.Request.Header.Peek("Access-Control-Request-Headers"))
if accessControlRequestHeaders != "" {
res.Header.Set("Access-Control-Allow-Headers", accessControlRequestHeaders)
}
res.Header.Set("Content-Length", "0")
res.SetStatusCode(204)
}
res.WriteTo(ctx.Conn())
defer fmt.Printf(
aurora.Sprintf(
"%s %s %s %s %s %s %d\n",
aurora.Magenta(ctx.Method()),
aurora.Blue("request proxied:"),
aurora.Green(ctx.RequestURI()),
aurora.Blue("->"),
aurora.Green(proxiedURI),
aurora.Blue("with status code"),
aurora.White(res.StatusCode()),
),
)
}