-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy.go
145 lines (126 loc) · 3.46 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
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
141
142
143
144
145
package routing
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/http/httputil"
"net/url"
"regexp"
"strconv"
"github.com/gin-gonic/gin"
validation "github.com/go-ozzo/ozzo-validation"
"github.com/jacekk/dead-simple-proxy-server/pkg/compression"
"github.com/jacekk/dead-simple-proxy-server/pkg/helpers"
"github.com/jacekk/dead-simple-proxy-server/pkg/storage"
)
func isSlugValid(slug string) error {
return validation.Validate(slug,
validation.Required,
validation.Length(4, 50),
validation.Match(regexp.MustCompile("^[a-z0-9-]+$")),
)
}
func getProxyBySlug(ctx *gin.Context) {
slug := ctx.Param("slug")
if err := isSlugValid(slug); err != nil {
msg := fmt.Sprintf("Given 'slug' is NOT valid --> %s.", err)
ctx.String(http.StatusBadRequest, msg)
return
}
storedItem, err := storage.GetProxyConfigBySlug(slug)
if err != nil {
ctx.String(http.StatusBadRequest, "Slug not found.")
return
}
parsedURL, err := url.Parse(storedItem.URL)
if err != nil {
ctx.String(http.StatusBadGateway, "Wrong URL linked with this slug.")
return
}
if storedItem.IsCacheEnabled {
readCachedResponse(ctx, storedItem, parsedURL)
return
}
initURLProxy(ctx, storedItem, parsedURL)
}
func readCachedResponse(
ctx *gin.Context,
item storage.Item,
parsedURL *url.URL,
) {
bodyPath := storage.SlugCachePath(item.ID, "body")
headersPath := storage.SlugCachePath(item.ID, "headers")
body, err := ioutil.ReadFile(bodyPath)
if err != nil {
ctx.String(http.StatusInternalServerError, "Failed to read content from cache.")
return
}
gzipped, err := compression.GzipBytes(body)
if err != nil {
ctx.String(http.StatusInternalServerError, "Failed to gzip cached content.")
return
}
headers, err := ioutil.ReadFile(headersPath)
if err != nil {
ctx.String(http.StatusInternalServerError, "Failed to read cached headers.")
return
}
var parsedHeaders http.Header
err = json.Unmarshal(headers, &parsedHeaders)
if err != nil {
msg := fmt.Sprintf("Failed to parse headers from cache --> %s.", err)
ctx.String(http.StatusInternalServerError, msg)
return
}
for key, value := range parsedHeaders {
ctx.Writer.Header().Set(key, value[0])
}
ctx.Writer.Header().Set("Content-Encoding", "gzip")
ctx.String(http.StatusOK, string(gzipped))
}
func initURLProxy(
ctx *gin.Context,
config storage.Item,
parsedURL *url.URL,
) {
director := func(req *http.Request) {
req.Host = "" // this is required for some unknown reasons
req.Header.Set("X-Forwarded-Host", req.Header.Get("Host"))
req.URL.Host = parsedURL.Host
req.URL.Path = parsedURL.Path
req.URL.RawQuery = parsedURL.RawQuery
req.URL.Scheme = parsedURL.Scheme
}
responseModifier := func(resp *http.Response) error {
isCompressed := helpers.IsResponseCompressed(resp)
body, err := helpers.ReadResponseBody(resp)
if err != nil {
return err
}
if isCompressed {
body, err = compression.UngzipBytes(body)
if err != nil {
return err
}
}
for from, to := range config.BodyRewrite {
body = bytes.Replace(body, []byte(from), []byte(to), -1)
}
if isCompressed {
body, err = compression.GzipBytes(body)
if err != nil {
return err
}
}
resp.Body = ioutil.NopCloser(bytes.NewReader(body))
if !isCompressed {
resp.ContentLength = int64(len(body))
resp.Header.Set("Content-Length", strconv.Itoa(len(body)))
}
return nil
}
proxy := &httputil.ReverseProxy{Director: director, ModifyResponse: responseModifier}
proxy.ServeHTTP(ctx.Writer, ctx.Request)
}