-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
99 lines (85 loc) · 2.42 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
package main
import (
// "fmt"
"log"
"net/http"
"net/http/httputil"
"net/url"
"os"
"strings"
"github.com/gin-gonic/gin"
)
var allowedUrls = []string{
"http://localhost:3000",
"https://localhost:3000",
"https://crypt-web.web.app",
"https://crypt-web.web.app/",
}
// function to check whether the backendServer parameter is a valid url or not
func isValidUrl(urlString string) bool {
_, err := url.ParseRequestURI(urlString)
return err == nil
}
// function to check whether the request is coming from an allowed URL or not
func isAllowedUrl(origin string) bool {
for _, u := range allowedUrls {
if u == origin {
return true
}
}
return false
}
func process(c *gin.Context) {
// Extract the URL from request path
backendServer := strings.TrimLeft(c.Param("proxyPath"), "/")
// check if the URL is valid
if backendServer == "" || !isValidUrl(backendServer) {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Invalid backend URL in the path"})
return
}
// Check if the request is coming from an allowed Origin
origin := c.Request.Header.Get("Origin")
// fmt.Println("Origin: ", origin)
if !isAllowedUrl(origin) {
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "Unauthorized access"})
return
}
// Create a new proxy
remote, err := url.Parse(backendServer)
if err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Invalid backend URL in the path"})
return
}
proxy := httputil.NewSingleHostReverseProxy(remote)
proxy.Director = func(req *http.Request) {
req.Header = c.Request.Header
req.Header.Set("Origin", "")
req.Host = remote.Host
req.URL.Scheme = remote.Scheme
req.URL.Host = remote.Host
req.URL.Path = remote.Path
}
// Add CORS headers to the response
c.Header("Access-Control-Allow-Origin", "*")
// c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE")
// c.Header("Access-Control-Allow-Headers", "Content-Type")
// checking for unexpected errors
defer func() {
if r := recover(); r != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Unexpected Error Occurred"})
}
}()
// Serve the request via the proxy
proxy.ServeHTTP(c.Writer, c.Request)
}
func main() {
router := gin.Default()
router.Any("/*proxyPath", process)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
if err := router.Run(":" + port); err != nil {
log.Panicf("error: %s", err)
}
}