This repository has been archived by the owner on Aug 25, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
90 lines (73 loc) · 1.77 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
78
79
80
81
82
83
84
85
86
87
88
89
90
package main
import (
"crypto/tls"
"flag"
"fmt"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"strings"
"time"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
)
var (
flags = flag.NewFlagSet("corsproxy", flag.ExitOnError)
fSource = flags.String("source", "", "Remote source to proxy to")
fListen = flags.String("listen", "9090", "Local port to listen for this proxy service")
)
func main() {
flags.Parse(os.Args[1:])
if fSource == nil || *fSource == "" {
fmt.Println("-source cannot be empty")
os.Exit(1)
}
listen := *fListen
if strings.Index(listen, ":") < 0 {
listen = fmt.Sprintf("localhost:%s", listen)
}
r := chi.NewRouter()
r.Use(middleware.Logger)
r.Handle("/*", proxy())
fmt.Printf("Proxying API requests from http://%s to %s ...\n", listen, *fSource)
err := http.ListenAndServe(listen, r)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func proxy() http.Handler {
source, err := url.Parse(*fSource)
if err != nil {
fmt.Printf("error parsing -source host %s because %v", *fSource, err)
os.Exit(1)
}
director := func(req *http.Request) {
req.URL.Scheme = source.Scheme
req.URL.Host = source.Host
req.Host = source.Host
if req.Header.Get("Origin") != "" {
req.Header.Set("Origin", source.String())
}
}
modifyResponse := func(resp *http.Response) error {
resp.Header.Set("Access-Control-Allow-Origin", "*")
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 proxy
}