-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmain.go
182 lines (149 loc) · 4.55 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
package main
import (
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"strings"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
)
func main() {
_, hostEnvVariableExists := os.LookupEnv("IPFS_GATEWAY_HOST")
if !hostEnvVariableExists {
fmt.Println("Error: IPFS_GATEWAY_HOST environment variable not set")
os.Exit(1)
}
_, allowOriginsEnvVariableExists := os.LookupEnv("ALLOW_ORIGINS")
if !allowOriginsEnvVariableExists {
fmt.Println("Error: ALLOW_ORIGINS environment variable not set")
os.Exit(1)
}
_, apiKeyEnvVariableExists := os.LookupEnv("API_KEY")
if !apiKeyEnvVariableExists {
fmt.Println("Error: API_KEY environment variable not set")
os.Exit(1)
}
router := chi.NewRouter()
router.Use(middleware.Logger)
router.Use(middleware.RealIP, middleware.Recoverer, middleware.RedirectSlashes, middleware.RequestID, middleware.CleanPath)
router.NotFound(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte("Route does not exist"))
})
router.MethodNotAllowed(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusMethodNotAllowed)
_, _ = w.Write([]byte("Method not allowed"))
})
router.Get("/*", handleRequest)
router.Head("/*", handleRequest)
router.Options("/*", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
var port = envPortOr("3031")
log.Fatal(http.ListenAndServe(port, router))
}
func handleRequest(w http.ResponseWriter, r *http.Request) {
authHeader := r.Header.Get("Authorization")
// if no auth header is set or auth header is empty, return unauthorized
if authHeader == "" {
w.WriteHeader(http.StatusUnauthorized)
_, _ = w.Write([]byte("Unauthorized"))
return
}
API_KEY, _ := os.LookupEnv("API_KEY")
if authHeader != API_KEY {
w.WriteHeader(http.StatusUnauthorized)
_, _ = w.Write([]byte("Unauthorized"))
return
}
ipAddress, err := getIP(r)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte(fmt.Sprintf("Failed to get IP address: %s", err)))
return
}
allowOrigins, _ := os.LookupEnv("ALLOW_ORIGINS")
// if allowOrigins is set to * then allow all origins
if allowOrigins == "*" {
allowOrigins = ipAddress
}
if !strings.Contains(allowOrigins, ipAddress) {
w.WriteHeader(http.StatusForbidden)
_, _ = w.Write([]byte(fmt.Sprintf("IP address %s is not allowed to access this resource", ipAddress)))
return
}
w.Header().Set("Access-Control-Allow-Origin", "*")
var cidAndFilePath string
if strings.Contains(r.URL.Path, "/ipfs/") {
splitPath := strings.SplitN(r.URL.Path, "/ipfs/", 2)
if len(splitPath) < 2 {
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(fmt.Sprintf("Invalid pathname: %s", r.URL.Path)))
return
}
cidAndFilePath = splitPath[1]
} else {
cidAndFilePath = strings.TrimPrefix(r.URL.Path, "/")
}
ipfsGatewayHost, _ := os.LookupEnv("IPFS_GATEWAY_HOST")
ipfsURL := fmt.Sprintf("%s/ipfs/%s", ipfsGatewayHost, cidAndFilePath)
resp, err := http.Get(ipfsURL)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte(fmt.Sprintf("Failed to fetch IPFS URL: %s", ipfsURL)))
return
}
defer resp.Body.Close()
buffer := make([]byte, 512)
_, err = resp.Body.Read(buffer)
if err != nil && err != io.EOF {
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte(fmt.Sprintf("Failed to read IPFS response: %s", err)))
return
}
// Detect the content type
contentType := http.DetectContentType(buffer)
// If the content type is text/html but the content starts with <svg, it's probably an SVG file
if (strings.HasPrefix(string(buffer), "<svg")) || strings.HasSuffix(r.URL.Path, ".svg") {
contentType = "image/svg+xml"
}
// Set the Content-Type header
w.Header().Set("Content-Type", contentType)
_, _ = w.Write(buffer)
_, _ = io.Copy(w, resp.Body)
}
func getIP(r *http.Request) (string, error) {
ip := r.Header.Get("X-REAL-IP")
netIP := net.ParseIP(ip)
if netIP != nil {
return ip, nil
}
ips := r.Header.Get("X-FORWARDED-FOR")
splitIps := strings.Split(ips, ",")
for _, ip := range splitIps {
ip := strings.TrimSpace(ip)
netIP := net.ParseIP(ip)
if netIP != nil {
return ip, nil
}
}
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return "", err
}
netIP = net.ParseIP(ip)
if netIP != nil {
return ip, nil
}
return "", fmt.Errorf("no valid ip found")
}
func envPortOr(port string) string {
// If `PORT` variable in environment exists, return it
if envPort := os.Getenv("PORT"); envPort != "" {
return ":" + envPort
}
return ":" + port
}