-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcorsanywhere.go
140 lines (111 loc) · 3.07 KB
/
corsanywhere.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
package main
import (
"flag"
"fmt"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"time"
"github.com/go-chi/chi/v5"
)
var (
flags = flag.NewFlagSet("corsanywhere", flag.ExitOnError)
fPort = flags.String("port", "8080", "Local port to listen for this corsanywhere service")
)
func main() {
flags.Parse(os.Args[1:])
port := *fPort
fmt.Printf("CORS Anywhere started at http://localhost:%s\n", port)
err := http.ListenAndServe(fmt.Sprintf(":%s", port), CORSAnywhereHandler())
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func CORSAnywhereHandler() http.Handler {
r := chi.NewRouter()
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(corsAnywhereUsage))
})
r.Handle("/*", corsProxy())
return r
}
func corsProxy() http.Handler {
director := func(req *http.Request) {
corsURL := chi.URLParam(req, "*")
u, err := url.Parse(corsURL)
if err != nil {
return
}
req.URL.Scheme = u.Scheme
req.URL.Host = u.Host
req.URL.Path = u.Path
req.Host = u.Host
// NOTE: the req.Query will already be set properly for us
req.Header.Del("set-cookie")
req.Header.Del("set-cookie2")
}
modifyResponse := func(resp *http.Response) error {
resp.Header.Set("access-control-allow-origin", "*")
resp.Header.Set("access-control-max-age", "3000000")
return nil
}
proxy := &httputil.ReverseProxy{
Director: director,
ModifyResponse: modifyResponse,
}
proxy.Transport = &http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).Dial,
TLSHandshakeTimeout: 10 * time.Second,
// TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
corsURL := chi.URLParam(r, "*")
// Verify cors proxy url is valid
_, err := url.Parse(corsURL)
if err != nil {
respondError(w, r, "invalid cors proxy url")
return
}
// Handle pre-flight
if r.Method == "OPTIONS" {
handlePreflight(w, r)
return
}
// Require origin header
if r.Header.Get("origin") == "" {
respondError(w, r, "origin header is required on the request")
return
}
proxy.ServeHTTP(w, r)
})
}
func handlePreflight(w http.ResponseWriter, r *http.Request) {
setCORSHeaders(w, r)
w.WriteHeader(200)
}
func respondError(w http.ResponseWriter, r *http.Request, body string) {
setCORSHeaders(w, r)
w.WriteHeader(422)
w.Write([]byte(body))
}
func setCORSHeaders(w http.ResponseWriter, r *http.Request) {
w.Header().Set("access-control-allow-origin", "*")
w.Header().Set("access-control-max-age", "3000000")
if r.Header.Get("access-control-request-method") != "" {
w.Header().Set("access-control-allow-methods", r.Header.Get("access-control-request-method"))
}
if r.Header.Get("access-control-request-headers") != "" {
w.Header().Set("access-control-request-headers", r.Header.Get("access-control-request-headers"))
}
}
var corsAnywhereUsage = `cors-anywhere usage:
http://localhost:<port>/http(s)://your-domain.com/endpoint
Inspired by https://github.com/Redocly/cors-anywhere
`