-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
87 lines (73 loc) · 2.29 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
package main
import (
"crypto/sha256"
"fmt"
"io"
"log"
"net/http"
"os"
"github.com/joho/godotenv"
)
func main() {
// Load environment variables from the .env filet
if _, err := os.Stat(".env"); err == nil {
if err := godotenv.Load(); err != nil {
log.Fatal("Error loading .env file: ", err)
}
}
// Get the value of the PORT environment variable, or set a default value of "3000"
port := os.Getenv("PORT")
if port == "" {
os.Setenv("PORT", "3000")
port = "3000"
}
apiBaseURL := os.Getenv("API_BASE_URL")
apiKey := os.Getenv("API_KEY")
// Set default value for API base URL if not specified in the .env file
if apiBaseURL == "" {
apiBaseURL = "https://api.status.finance"
}
// Set up the HTTP handler that identifies the api key
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
identifier := sha256.Sum256([]byte(apiKey))
io.WriteString(w, fmt.Sprintf(`{"message": "Proxy for Status API", "identifier": "%x"}`, identifier))
})
// Set up the HTTP handler that proxies requests to the API
http.HandleFunc("/transactions", func(w http.ResponseWriter, r *http.Request) {
// Create a new request to the API endpoint
req, err := http.NewRequest(r.Method, apiBaseURL+"/transactions", r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Do not proxy all headers for privacy reasons
//req.Header = r.Header
req.URL.RawQuery = r.URL.RawQuery
// Set the x-api-key header on the new request
req.Header.Set("x-api-key", apiKey)
// Send the new request and get the response
res, err := http.DefaultClient.Do(req)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer res.Body.Close()
// Read the response body from the API into a []byte
body, err := io.ReadAll(res.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Write the response from the API to the original response writer
w.WriteHeader(res.StatusCode)
if _, err := w.Write(body); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
})
// Start the HTTP server
log.Println("Listening on http://localhost:" + port + "...")
if err := http.ListenAndServe(":"+port, nil); err != nil {
log.Fatal(err)
}
}