forked from mvazquezc/reverse-words
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
151 lines (137 loc) · 4.01 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
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"github.com/gorilla/mux"
"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: "total_reversed_words",
Help: "Total number of reversed words",
},
)
)
var (
endpointsAccessed = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "endpoints_accessed",
Help: "Total number of accessed to a given endpoint",
},
[]string{"accessed_endpoint"},
)
)
var version = "v0.0.40"
// 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
_, 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)
}
//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)
log.Println("Listening on port", port)
prometheus.MustRegister(totalWordsReversed)
prometheus.MustRegister(endpointsAccessed)
router := mux.NewRouter()
router.HandleFunc("/", ReverseWord).Methods("POST")
router.HandleFunc("/", ReturnRelease).Methods("GET")
router.HandleFunc("/hostname", ReturnHostname).Methods("GET")
router.HandleFunc("/health", ReturnHealth).Methods("GET")
router.Handle("/metrics", promhttp.Handler()).Methods("GET")
log.Fatal(http.ListenAndServe(":"+port, router))
}