forked from tolson-vkn/env-echgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
112 lines (87 loc) · 2.36 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
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"strings"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
type echgoHandler struct {
echgos []byte
metrics *prometheus.CounterVec
}
func errorHandler(res http.ResponseWriter, req *http.Request, status int) {
res.WriteHeader(status)
notFound := make(map[string]string)
notFound["message"] = "Hey what're you doing use the default route: /"
nf, err := json.Marshal(notFound)
if err != nil {
log.Fatalf("err: %s\n", err)
}
if status == http.StatusNotFound {
res.Write(nf)
}
}
func (h echgoHandler) ServeHTTP(res http.ResponseWriter, req *http.Request) {
header := res.Header()
header.Set("Content-Type", "application/json")
log.Printf("%s %s %s User-Agent: %s\n", req.Method, req.Proto, req.URL.Path, req.Header["User-Agent"])
if req.URL.Path != "/" {
h.metrics.WithLabelValues("fail").Inc()
errorHandler(res, req, http.StatusNotFound)
return
}
h.metrics.WithLabelValues("success").Inc()
res.WriteHeader(200)
res.Write(h.echgos)
}
func registerEchgos() map[string]string {
registered := make(map[string]string)
for _, s := range os.Environ() {
split := strings.Split(s, "=")
if strings.HasPrefix(split[0], "ECHGO") {
eKey := strings.Split(split[0], "ECHGO_")
if len(eKey) != 2 {
log.Printf("Envar [%s] malformed, skipping\n", s)
continue
}
key := eKey[1]
key = strings.ToLower(key)
if key == "message" {
log.Printf("Key [%s] is reserverd, skipping\n", key)
continue
}
value := split[1]
registered[key] = value
log.Printf("Processed envar [%s] as key: [%s], value: [%s]\n", s, key, value)
}
}
return registered
}
func main() {
registered := registerEchgos()
registered["message"] = "Hello from Ecgho Server"
echgos, err := json.Marshal(registered)
if err != nil {
log.Fatalf("err: %s\n", err)
}
log.Printf("Registered: %s", echgos)
promCounter := prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "root_requests_total",
Help: "Hits to the root echo path",
},
[]string{"status"},
)
prometheus.MustRegister(promCounter)
mux := http.NewServeMux()
mux.Handle("/", &echgoHandler{echgos: echgos, metrics: promCounter})
mux.Handle("/metrics", promhttp.Handler())
server := &http.Server{
Addr: ":8080",
Handler: mux,
}
server.ListenAndServe()
}