-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproxy.go
99 lines (77 loc) · 2.16 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package simple
import (
"errors"
"fmt"
"net/http"
"net/http/httputil"
"net/url"
)
type Proxy struct {
*Simple
}
func DefaultProxy() *Proxy {
return &Proxy{
Simple: Default(),
}
}
func NewProxy() *Proxy {
return &Proxy{
Simple: New(),
}
}
func isValidUrl(u1 string) bool {
_, err := url.ParseRequestURI(u1)
if err != nil {
return false
}
u, err := url.Parse(u1)
if err != nil || u.Scheme == "" || u.Host == "" {
return false
}
if u.Scheme != "http" && u.Scheme != "https" {
return false
}
return true
}
func (p *Proxy) AddRoute(method, proxyPath, target string, handlers ...HandlerFunc) {
if !isValidUrl(target) {
panic(errors.New("invalid target url"))
}
proxyHandler := func(c *Context) {
if len(c.Path) < len(proxyPath) {
c.Status(http.StatusNotFound).
String("%s: %s", http.StatusText(http.StatusNotFound), c.Path)
return
}
targetPath := c.Path[len(proxyPath):]
targetUrl, err := url.Parse(fmt.Sprintf("%s/%s", target, targetPath))
if err != nil {
panic(err)
}
proxy := httputil.NewSingleHostReverseProxy(targetUrl)
c.Req.URL.Path = "/"
proxy.ServeHTTP(c.Writer, c.Req)
}
p.router.addRoute(method, proxyPath+"/*", append(handlers, proxyHandler))
}
func (p *Proxy) GET(proxyPath, target string, handlers ...HandlerFunc) {
p.AddRoute(http.MethodGet, proxyPath, target, handlers...)
}
func (p *Proxy) POSR(proxyPath, target string, handlers ...HandlerFunc) {
p.AddRoute(http.MethodPost, proxyPath, target, handlers...)
}
func (p *Proxy) PUT(proxyPath, target string, handlers ...HandlerFunc) {
p.AddRoute(http.MethodPut, proxyPath, target, handlers...)
}
func (p *Proxy) DELETE(proxyPath, target string, handlers ...HandlerFunc) {
p.AddRoute(http.MethodDelete, proxyPath, target, handlers...)
}
func (p *Proxy) PATCH(proxyPath, target string, handlers ...HandlerFunc) {
p.AddRoute(http.MethodPatch, proxyPath, target, handlers...)
}
func (p *Proxy) Options(proxyPath, target string, handlers ...HandlerFunc) {
p.AddRoute(http.MethodOptions, proxyPath, target, handlers...)
}
func (p *Proxy) Head(proxyPath, target string, handlers ...HandlerFunc) {
p.AddRoute(http.MethodHead, proxyPath, target, handlers...)
}