-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
210 lines (181 loc) · 4.89 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
package main
import (
"context"
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
"strconv"
"strings"
"text/template"
terraminogo "github.com/hashicorp-education/terraminogo/internal"
"github.com/redis/go-redis/v9"
)
type TerraminoData struct {
HVSClient *terraminogo.HVSClient
redisClient *redis.Client
ctx context.Context
appName string
}
func main() {
t := &TerraminoData{}
t.HVSClient = terraminogo.NewHVSClient()
t.redisClient = nil
t.ctx = context.Background()
appName, envExists := os.LookupEnv("APP_NAME")
if !envExists {
appName = "terramino"
}
t.appName = appName
http.HandleFunc("/", indexHandler)
http.HandleFunc("/env", envHandler)
http.HandleFunc("/score", t.highScoreHandler)
http.HandleFunc("/redis", t.redisHandler)
http.HandleFunc("/{path}", pathHandler)
envPort, envPortExists := os.LookupEnv("TERRAMINO_PORT")
if !envPortExists {
envPort = "8080"
}
port := fmt.Sprintf(":%s", envPort)
fmt.Printf("Terramino server is running on http://localhost%s\n", port)
err := http.ListenAndServe(port, nil)
if err != nil {
log.Fatal(err)
}
}
// Parse and serve index template
func indexHandler(w http.ResponseWriter, r *http.Request) {
t, err := template.ParseFiles("web/index.html")
if err != nil {
log.Fatal(err)
}
err = t.ExecuteTemplate(w, "index.html", nil)
if err != nil {
log.Fatal(err)
}
}
// Handle non-template files
func pathHandler(w http.ResponseWriter, r *http.Request) {
filePath, err := fileLookup(r.PathValue("path"))
if err != nil {
// User requested a file that does not exist
// Return 404
if errors.Is(err, os.ErrNotExist) {
w.WriteHeader(404)
return
} else {
// Unknown error
log.Fatal(err)
}
}
http.ServeFile(w, r, filePath)
}
func (t *TerraminoData) highScoreHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
score := t.GetHighScore()
w.Write([]byte(strconv.Itoa(score)))
} else if r.Method == "POST" {
newScore, _ := io.ReadAll(r.Body)
iNewScore, _ := strconv.Atoi(string(newScore))
iOldScore := t.GetHighScore()
if iNewScore > iOldScore {
t.SetHighScore(iNewScore)
w.Write(newScore)
} else {
w.Write([]byte(strconv.Itoa(iOldScore)))
}
} else if r.Method == "PUT" {
newScore, _ := io.ReadAll(r.Body)
iNewScore, _ := strconv.Atoi(string(newScore))
t.SetHighScore(iNewScore)
w.Write(newScore)
}
}
func (t *TerraminoData) getRedisClient() *redis.Client {
if t.redisClient != nil {
// We have an existing connection, make sure it's still valid
pingResp := t.redisClient.Ping(t.ctx)
if pingResp.Err() == nil {
// Connection is valid, return client
return t.redisClient
}
}
// Either we don't have a connection, or it's no longer valid
// Create a new client
// Check for connection info in HVS
redisIP, err := t.HVSClient.GetSecret(t.appName, "redis_ip")
if err != nil {
// No Redis server is available
t.redisClient = nil
return nil
}
redisPort, _ := t.HVSClient.GetSecret(t.appName, "redis_port")
redisPassword, _ := t.HVSClient.GetSecret(t.appName, "redis_password")
t.redisClient = redis.NewClient(&redis.Options{
Addr: fmt.Sprintf("%s:%s", redisIP, redisPort),
Password: redisPassword,
DB: 0,
})
// Check connection
pingResp := t.redisClient.Ping(t.ctx)
if pingResp.Err() != nil {
// Error connecting to the server
log.Println(pingResp.Err())
return nil
}
return t.redisClient
}
func (t *TerraminoData) GetHighScore() int {
redisClient := t.getRedisClient()
if redisClient != nil {
val, err := redisClient.Get(t.ctx, "score").Result()
if err == nil {
iVal, _ := strconv.Atoi(val)
return iVal
}
}
return 0
}
func (t *TerraminoData) SetHighScore(score int) {
redisClient := t.getRedisClient()
if redisClient != nil {
redisClient.Set(t.ctx, "score", score, 0)
}
}
// Lookup requested file, return an error if it
// does not exist
func fileLookup(file string) (string, error) {
fullPath := fmt.Sprintf("web/%s", file)
_, err := os.Stat(fullPath)
if err != nil {
return "", err
} else {
return fullPath, nil
}
}
// DEBUG: Print all runtime environment variables that start with "HCP_"
func envHandler(w http.ResponseWriter, r *http.Request) {
out := ""
for _, e := range os.Environ() {
// Split the environment variable into key and value
pair := strings.SplitN(e, "=", 2)
if strings.HasPrefix(pair[0], "HCP_") {
out += fmt.Sprintf("%s\n", e)
}
}
out += fmt.Sprintf("APP_NAME=%s\n", os.Getenv("APP_NAME"))
w.Write([]byte(out))
}
func (t *TerraminoData) redisHandler(w http.ResponseWriter, r *http.Request) {
redisHost, _ := t.HVSClient.GetSecret(t.appName, "redis_ip")
redisPort, _ := t.HVSClient.GetSecret(t.appName, "redis_port")
redisPing := "No connection"
redisClient := t.getRedisClient()
if redisClient != nil {
pingResp := redisClient.Ping(t.ctx)
redisPing = pingResp.String()
}
fmt.Fprintf(w, "redis_host=%s\nredis_port=%s\n\nConnection: %s", redisHost, redisPort, redisPing)
}