/
main.go
239 lines (200 loc) · 5.71 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
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
package main
import (
"crypto/md5"
b64 "encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strconv"
"time"
"github.com/3n3a/httpproxy-cache-api/modules/utils"
hReq "github.com/imroc/req/v3"
"github.com/redis/go-redis/v9"
"github.com/uptrace/bunrouter"
"github.com/uptrace/bunrouter/extra/reqlog"
)
type Server struct {
ProxyPath string
Config map[string]string
RedisClient utils.Redis
}
func (s *Server) Init() {
s.ProxyPath = os.Getenv("APP_CONFIG_PATH")
s.readConfig()
port, err := strconv.ParseInt(s.getConfigValue("port").(string), 0, 0)
if err != nil {
panic("Error while parsing port from configuration")
}
router := bunrouter.New(
bunrouter.Use(reqlog.NewMiddleware(
reqlog.FromEnv("BUNDEBUG"),
)),
bunrouter.WithNotFoundHandler(notFoundHandler),
bunrouter.WithMethodNotAllowedHandler(methodNotAllowedHandler),
)
s.RedisClient = utils.Redis{}
s.RedisClient.Init(s.getConfigValue("redis-url").(string))
router.GET("/v1/ping", s.pingHandler)
router.GET("/v1/p/:key/*path", s.proxyHandler)
router.POST("/v1/p/:key/*path", s.proxyHandler)
router.PUT("/v1/p/:key/*path", s.proxyHandler)
router.DELETE("/v1/p/:key/*path", s.proxyHandler)
router.HEAD("/v1/p/:key/*path", s.proxyHandler)
router.OPTIONS("/v1/p/:key/*path", s.proxyHandler)
fmt.Printf("Listening on http://localhost:%d\n", port)
http.ListenAndServe(fmt.Sprintf(":%d", port), router)
}
func main() {
server := Server{}
server.Init()
}
func (s *Server) readConfig() {
if len(s.ProxyPath) <= 0 {
panic("Proxy Configuration Path is empty")
}
var err error
s.Config, err = utils.ReadYAMLIntoStruct[map[string]string](s.ProxyPath)
if err != nil {
panic("Configuration not found")
}
}
func (s *Server) getConfigValue(key string) any {
return s.Config[key]
}
func (s *Server) pingHandler (w http.ResponseWriter, req bunrouter.Request) error {
value, err := s.RedisClient.Get("counter")
if err == redis.Nil {
s.RedisClient.Set("counter", 0, 5*time.Hour)
}
counter, _ := strconv.Atoi(value)
counter++
s.RedisClient.Set("counter", counter, 5*time.Hour)
fmt.Println(counter)
fmt.Fprintf(
w,
"pong",
)
return nil
}
func (s *Server) proxyHandler(w http.ResponseWriter, req bunrouter.Request) error {
// Get Base Url for Key
key := req.Param("key")
path := req.Param("path")
urlMap, err := utils.ReadYAMLIntoStruct[map[string]string](
s.getConfigValue("proxy-path").(string),
)
url := urlMap[key]
if err != nil {
fmt.Println("File not found")
}
builtUrl := fmt.Sprintf("%s/%s", url, path)
// Read Input Body
defer req.Body.Close()
reqBody, err := io.ReadAll(req.Body)
if err != nil {
fmt.Println("Error reading req body")
}
// Hash the Body
headerJSON, err := json.Marshal(req.Header)
if err != nil {
fmt.Println("Headers couldnt be converted to JSON.")
}
rawBodyHash := md5.Sum(reqBody) //, []byte(builtUrl), []byte(req.Method), []byte(headerJSON)}, []byte(" ")))
rawUrlHash := md5.Sum([]byte(builtUrl))
rawHeaderHash := md5.Sum(headerJSON)
reqMethodsHash := md5.Sum([]byte(req.Method))
bodyHash := fmt.Sprintf("%x", md5.Sum([]byte(fmt.Sprintf("%x-%x-%x-%x", rawBodyHash, rawUrlHash, reqMethodsHash, rawHeaderHash))))
// Header Key
headerKey := fmt.Sprintf("%s-header", bodyHash)
cachedValue, err := s.RedisClient.Get(bodyHash)
if err == redis.Nil {
fmt.Println("Requesting from origin")
// Proxy Request Headers & Body
client := hReq.C()
client.Headers = req.Header
cReq := client.R()
cReq.Method = req.Method
cReq.SetURL(builtUrl)
cReq.SetBody(reqBody)
res := cReq.Do()
err = res.Err
if err != nil {
fmt.Printf("Error Req: %s\n", err.Error())
}
// Proxy Response Headers
for headerKey, headerValue := range res.Response.Header {
w.Header().Add(headerKey, headerValue[0])
}
// Proxy Response Body
w.Write(res.Bytes())
// Cache Body
encodedValue := b64.StdEncoding.EncodeToString(res.Bytes())
s.RedisClient.Set(bodyHash, encodedValue, 24*time.Hour)
// Cache Headers
jsonHeaders, err := json.Marshal(res.Response.Header)
if err != nil {
fmt.Println("Failed to marshal headers, Json.")
}
encodedHeaders := b64.StdEncoding.EncodeToString(jsonHeaders)
s.RedisClient.Set(headerKey, encodedHeaders, 24*time.Hour)
} else {
// B64 Decode Body
fmt.Println("Returning cached response")
decodedValue, err := b64.StdEncoding.DecodeString(cachedValue)
if err != nil {
fmt.Println("Error decoding b64 value;", err)
}
// Get Headers from Cache
cachedHeaders, err := s.RedisClient.Get(headerKey)
if err != nil {
fmt.Println("Failed to get header valzue")
}
// B64 Decode Headers
jsonHeaders, err := b64.StdEncoding.DecodeString(cachedHeaders)
if err != nil {
fmt.Println("Failed to b564 decode headers")
}
// JSON Unmarshal Headers
var decodedHeaders map[string][]string
err = json.Unmarshal(jsonHeaders, &decodedHeaders)
if err != nil {
fmt.Println("Failed to unmarshal headers")
}
// Add Headers to HTTP Response
for headerKey, headerValue := range decodedHeaders {
w.Header().Add(headerKey, headerValue[0])
}
// Add Header Telling that was from Cache
w.Header().Add("X-Served-By", "HTTP Proxy Cache API V1.0.0")
w.Write(decodedValue)
}
return nil
}
func notFoundHandler(w http.ResponseWriter, req bunrouter.Request) error {
return utils.JSON(
w,
bunrouter.H{
"message": "route not found",
"info": bunrouter.H{
"path": req.URL.Path,
"method": req.Method,
},
},
http.StatusNotFound,
)
}
func methodNotAllowedHandler(w http.ResponseWriter, req bunrouter.Request) error {
return utils.JSON(
w,
bunrouter.H{
"message": "route found, but method not allowed",
"info": bunrouter.H{
"path": req.URL.Path,
"method": req.Method,
},
},
http.StatusMethodNotAllowed,
)
}