-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
188 lines (148 loc) · 4.52 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
////////////////////////////////////////////////////////
// Simple Go Rest API Service
// author: A.Davarski
////////////////////////////////////////////////////////
package main
import (
"encoding/json"
"io"
"log"
"math/rand"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/gorilla/mux"
)
type JQuotes struct {
QList []JQuote `json:"quotes"`
}
type JQuote struct {
Author string `json:"author"`
Text string `json:"text"`
}
func HealthCheck(w http.ResponseWriter, r *http.Request) {
/*
HealthCheck endpoint will return the Health Status.
By default, It provides the status as healthy. (If container running properly)
*/
log.Println("Entering /health-check endpoint, Invoked from", r.RemoteAddr)
// Add delay to /health-check API
hDelay, ok := getEnv("HEALTHDELAY")
if !ok {
hDelay = "0"
}
iDelay, err := strconv.Atoi(hDelay)
if err != nil || iDelay == 0 {
json.NewEncoder(w).Encode(map[string]bool{"healthy": true})
} else {
time.Sleep(time.Duration(iDelay) * time.Second)
log.Println("Added", hDelay, "seconds delay, Serving Requst Now")
json.NewEncoder(w).Encode(map[string]bool{"healthy": true})
}
}
func Info(w http.ResponseWriter, r *http.Request) {
/*
/info endpoint will return request info.
*/
log.Println("Entering /info endpoint, Invoked from", r.RemoteAddr)
remoteIP := r.RemoteAddr //requesterIP
rMethod := r.Method
rURI := r.RequestURI
infoResp := make(map[string]string)
infoResp["Version"] = os.Getenv("VERSION")
infoResp["RemoteIP"] = remoteIP
infoResp["Method"] = rMethod
infoResp["Endpoint"] = rURI
infoResp["Host"] = r.Host
// Or you can also make the map like this.
// infoResp := map[string]string{"Version": os.Getenv("VERSION"), "RemoteIP": remoteIP, "Method": rMethod, "Endpoint": rURI}
json.NewEncoder(w).Encode(infoResp)
}
func Env(w http.ResponseWriter, r *http.Request) {
/*
/env endpoint will dump the environment variables.
*/
log.Println("Entering /env endpoint, Invoked from", r.RemoteAddr)
resp := make(map[string]string)
resp["Version"] = os.Getenv("VERSION")
// dump the enviroment variables.
// os.Environ() returns the slice of strings, So join them using strings.Join to make a string.
resp["env"] = strings.Join(os.Environ(), ", ")
json.NewEncoder(w).Encode(resp)
}
func Quote(w http.ResponseWriter, r *http.Request) {
/*
/quote endpoint will return random quote.
*/
fileName, ok := getEnv("QUOTESFILE")
if !ok {
fileName = "./quotes.json"
}
log.Println("Entered /quote endpoint, Invoked from", r.RemoteAddr, ", using", fileName, "as QuotesSource")
file, err := os.Open(fileName)
if err != nil {
log.Fatalf("Not able to open %s file", fileName)
}
jsonQuotes, err := getJsonQuotes(file)
if err != nil {
log.Fatalf("Failed to decode the JSON %s", err)
}
// Get a random quote from "jsonQuotes"
// Pass the time as the seed for random generator
rand.Seed(time.Now().UnixNano())
// Generate random index from 0 to lenght of the quote array
rNum := rand.Intn(len(jsonQuotes.QList) - 1)
rQuote := jsonQuotes.QList[rNum]
// Prepare and Send the response back
resp := make(map[string]string)
resp["Version"] = os.Getenv("VERSION")
resp["Quote"] = rQuote.Text + " - " + rQuote.Author
log.Println(resp["Quote"])
json.NewEncoder(w).Encode(resp)
}
// Parse json file and decode into the Story struct
func getJsonQuotes(file io.Reader) (JQuotes, error) {
d := json.NewDecoder(file)
var jsonQuotes JQuotes
if err := d.Decode(&jsonQuotes); err != nil {
return JQuotes{}, err
}
return jsonQuotes, nil
}
func getEnv(key string) (string, bool) {
val, ok := os.LookupEnv(key)
if !ok {
// 'key' like "PORT" env not set return default value "10000"
return "", false
} else {
return val, true
}
}
func main() {
// Set the version of the API and Port
os.Setenv("VERSION", "1.0.0")
router := mux.NewRouter()
// router.HandleFunc("/", HomeRouter).Methods("GET")
router.HandleFunc("/health-check", HealthCheck).Methods("GET")
router.HandleFunc("/info", Info).Methods("GET")
router.HandleFunc("/env", Env).Methods("GET")
router.HandleFunc("/quote", Quote).Methods("GET")
http.Handle("/", router)
port, ok := getEnv("PORT")
if !ok {
port = "10000"
}
// Our service listens on All interfaces of host
addr := "0.0.0.0:" + port
log.Printf("Simple API Server(%s) running on %s", os.Getenv("VERSION"), addr)
srv := &http.Server{
Handler: router,
Addr: addr, // localhost
// Good practice: enforce timeouts for servers you create!
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
log.Fatal(srv.ListenAndServe())
}