-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproxy.go
86 lines (70 loc) · 1.56 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
package main
import (
"compress/gzip"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"time"
)
var tr = &http.Transport{
MaxIdleConns: 10,
IdleConnTimeout: 30 * time.Second,
DisableCompression: true,
}
var client = &http.Client{Transport: tr}
func proxyHandler(w http.ResponseWriter, r *http.Request) {
url := r.URL.Query().Get("u")
if r.Method == "GET" {
req, err := http.NewRequest(r.Method, url, nil)
if err != nil {
writeError(w, "Could not create request")
return
}
req.Header = r.Header
var toRead io.ReadCloser
resp, err := client.Do(req)
if err != nil {
writeError(w, "Could not make request to client")
return
}
if resp.Header.Get("Content-Encoding") == "gzip" {
gzipReader, err := gzip.NewReader(resp.Body)
if err != nil {
writeError(w, "Coult not create gzip reader")
return
}
toRead = gzipReader
} else {
toRead = resp.Body
}
defer toRead.Close()
byteBody, err := ioutil.ReadAll(toRead)
checkErr(err)
// TODO: if Accept-Encoding gzip
// write gzipped data
fmt.Fprintf(w, string(byteBody))
} else {
writeError(w, "POST not yet supported")
}
}
func writeError(w http.ResponseWriter, errStr string) {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, genError(errStr))
}
func main() {
http.HandleFunc("/", proxyHandler)
var port string
if os.Getenv("PORT") != "" {
port = ":" + os.Getenv("PORT")
} else {
port = ":8080"
}
startServer(port)
}
func startServer(port string) {
fmt.Printf("Listening on port %s", port)
log.Fatal(http.ListenAndServe(port, nil))
}