-
Notifications
You must be signed in to change notification settings - Fork 115
/
main.go
168 lines (152 loc) · 4.96 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
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"github.com/go-chi/chi/v5"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
// Input word
type Input struct {
Word string `json:"word,omitempty"`
}
// Output reverse word
type Output struct {
ReverseWord string `json:"reverse_word,omitempty"`
}
var (
totalWordsReversed = prometheus.NewCounter(
prometheus.CounterOpts{
Name: "reversewords_reversed_words_total",
Help: "Total number of reversed words",
},
)
)
var (
endpointsAccessed = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "reversewords_endpoints_accessed_total",
Help: "Total number of accessed to a given endpoint",
},
[]string{"accessed_endpoint"},
)
)
const version = "v0.0.27"
var (
buildTime = "NotSet"
gitCommit = "NotSet"
)
// ReturnRelease returns the release configured by the user
func ReturnRelease(w http.ResponseWriter, r *http.Request) {
release := getEnv("RELEASE", "NotSet")
releaseString := "Reverse Words Release: " + release + ". App version: " + version + ". Build Time: " + buildTime + ". Git Commit: " + gitCommit
_, err := w.Write([]byte(releaseString + "\n"))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
endpointsAccessed.WithLabelValues("release").Inc()
}
// ReturnHostname returns the hostname for the node where the app is running
func ReturnHostname(w http.ResponseWriter, r *http.Request) {
hostname, err := os.Hostname()
if err != nil {
hostname = "Unknown"
}
hostnameString := "Hostname: " + hostname
_, err = w.Write([]byte(hostnameString + "\n"))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
endpointsAccessed.WithLabelValues("hostname").Inc()
}
// ReturnHealth returns healthy string, can be used for monitoring pourposes
func ReturnHealth(w http.ResponseWriter, r *http.Request) {
health := "Healthy"
_, err := w.Write([]byte(health + "\n"))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
endpointsAccessed.WithLabelValues("health").Inc()
}
// ReverseWord returns a reversed word based on an input word
func ReverseWord(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
var word Input
var reverseWord string
err := decoder.Decode(&word)
if err != nil {
// Error EOF means no json data has been sent
if err.Error() != "EOF" {
panic(err)
}
}
if len(word.Word) < 1 {
log.Println("No word detected, sending default reverse word")
reverseWord = "detceted drow oN"
} else {
log.Println("Detected word", word.Word)
reverseWord = reverse(word.Word)
}
log.Println("Reverse word", reverseWord)
totalWordsReversed.Inc()
output := Output{reverseWord}
js, err := json.Marshal(output)
js = append(js, "\n"...)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
_, err = w.Write([]byte(js))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
endpointsAccessed.WithLabelValues("reverseword").Inc()
}
// reverse returns input string reversed
func reverse(s string) string {
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}
func listen(port string, registry *prometheus.Registry) {
log.Println("Listening on port", port)
router := chi.NewRouter()
router.Get("/", ReturnRelease)
router.Post("/", ReverseWord)
router.Get("/hostname", ReturnHostname)
router.Get("/health", ReturnHealth)
router.Mount("/fullmetrics", promhttp.Handler()) // Default prometheus collector, includes other stuff on top of our custom registers
router.Mount("/metrics", promhttp.HandlerFor(registry, promhttp.HandlerOpts{}))
log.Fatal(http.ListenAndServe(":"+port, router))
}
// getEnv returns the value for a given Env Var
func getEnv(varName, defaultValue string) string {
if varValue, ok := os.LookupEnv(varName); ok {
return varValue
}
return defaultValue
}
func main() {
release := getEnv("RELEASE", "NotSet")
port := getEnv("APP_PORT", "8080")
log.Println("Starting Reverse Api", version, "Release:", release, "Commit", gitCommit, "Build", buildTime)
// Custom registry, this will be used by the /metrics endpoint and will only show the app metrics
registry := prometheus.NewRegistry()
// Add our custom registers to our custom registry
registry.MustRegister(totalWordsReversed, endpointsAccessed)
// Add our custom registers to the default register, this will be used by the /fullmetrics endpoints
prometheus.MustRegister(totalWordsReversed, endpointsAccessed)
// Remove the go/process collectors from the default prometheus registry, this can be used to remove collectos from the default prometheus registry
//prometheus.Unregister(collectors.NewGoCollector())
//prometheus.Unregister(collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}))
listen(port, registry)
}