-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
73 lines (50 loc) · 1.41 KB
/
Copy pathmain.go
File metadata and controls
73 lines (50 loc) · 1.41 KB
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
package main
import (
"flag"
"fmt"
"io"
"log"
"net/http"
"time"
"github.com/gofiber/fiber/v2"
"github.com/patrickmn/go-cache"
)
func main() {
port := flag.Int("port", 8080, "Port to run the proxy server on")
origin := flag.String("origin", "", "Origin server to forward requests to (required)")
flag.Parse()
if *origin == "" {
log.Fatal("Error: --origin is required")
}
var respCache = cache.New(60*time.Second, 120*time.Second)
app := fiber.New()
app.Get("/*", func(c *fiber.Ctx) error {
url := fmt.Sprintf("%s%s", *origin, c.OriginalURL())
// url := c.Query("url")
// if url == "" {
// return c.Status(400).SendString("Missing URL")
// }
if cachedResp, found := respCache.Get(url); found {
c.Set("X-Cache", "HIT")
return c.Send(cachedResp.([]byte))
}
resp, err := http.Get(url)
if err != nil || resp.StatusCode != 200 {
return c.Status(502).SendString("Bad Gateway")
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
// Save to cache
respCache.Set(url, body, cache.DefaultExpiration)
c.Set("X-Cache", "MISS")
return c.Send(body)
})
// app.Get("/", func(c *fiber.Ctx) error {
// return c.Status(200).SendString("Hello, World!")
// })
// app.Listen(":5000")
// fmt.Println("Server running on port 5000")
addr := fmt.Sprintf(":%d", *port)
log.Printf("Starting caching proxy on %s, forwarding to %s\n", addr, *origin)
log.Fatal(app.Listen(addr))
}