forked from nlamirault/podtato-head
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
155 lines (121 loc) · 3.66 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
package main
import (
"flag"
"fmt"
"os"
"strconv"
"time"
"github.com/podtato-head/podtato-head-server/pkg"
"github.com/gorilla/mux"
"html/template"
"log"
"net/http"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
const (
StaticAssetsPathEnvVar = "STATIC_ASSETS_PATH"
StaticAssetsPathDefault = "./static"
StaticAssetsURLPathPrefix = "/static"
)
var staticAssetsPath string
var podtatoConfiguration *pkg.PodtatoConfig
// HTML page template
var overviewTemplate *template.Template
// create a new counter vector
var getCallCounter = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "http_requests_total", // metric name
Help: "Number of get requests.",
},
[]string{"status"}, // labels
)
var buckets = []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5, 10}
var responseTimeHistogram = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: "http_server_request_duration_seconds",
Help: "Histogram of response time for handler in seconds",
Buckets: buckets,
}, []string{"route", "method", "status_code"})
// create a handler struct
type HTTPHandler struct{}
type statusRecorder struct {
http.ResponseWriter
statusCode int
}
func (rec *statusRecorder) WriteHeader(statusCode int) {
rec.statusCode = statusCode
rec.ResponseWriter.WriteHeader(statusCode)
}
func getRoutePattern(r *http.Request) string {
reqContext := mux.CurrentRoute(r)
if pattern, _ := reqContext.GetPathTemplate(); pattern != "" {
return pattern
}
fmt.Println(reqContext.GetPathRegexp())
return "undefined"
}
// implement `ServeHTTP` method on `HttpHandler` struct
func (h HTTPHandler) ServeHTTP(res http.ResponseWriter, req *http.Request) {
var status string
defer func() {
// increment the counter on defer func
getCallCounter.WithLabelValues(status).Inc()
}()
overviewTemplate = template.Must(template.ParseFiles(fmt.Sprintf("%s/podtato-new.html", staticAssetsPath)))
err := overviewTemplate.Execute(res, podtatoConfiguration)
if err != nil {
log.Print(err.Error())
}
// Slow build
if podtatoConfiguration.ServiceVersion == "0.1.2" {
time.Sleep(400 * time.Millisecond)
}
if err != nil {
status = "error"
}
status = "success"
}
func prometheusMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
rec := statusRecorder{w, 200}
next.ServeHTTP(&rec, r)
duration := time.Since(start)
statusCode := strconv.Itoa(rec.statusCode)
route := getRoutePattern(r)
fmt.Println(duration.Seconds())
responseTimeHistogram.WithLabelValues(route, r.Method, statusCode).Observe(duration.Seconds())
})
}
func init() {
prometheus.Register(getCallCounter)
prometheus.Register(responseTimeHistogram)
staticAssetsPath = os.Getenv(StaticAssetsPathEnvVar)
if len(staticAssetsPath) == 0 {
staticAssetsPath = StaticAssetsPathDefault
}
}
func main() {
// expecting version as first parameter
serviceVersion := flag.String("version", "", "Service version e.g. 0.1.0")
flag.Parse()
var err error
podtatoConfiguration, err = pkg.GetAssembledPodtatoConfiguration(*serviceVersion)
if err != nil {
log.Fatal(err)
}
// create a new handler
handler := HTTPHandler{}
router := mux.NewRouter()
router.Use(prometheusMiddleware)
router.Path("/").Handler(handler)
router.Path("/")
// Serving static files
router.
PathPrefix(StaticAssetsURLPathPrefix).
Handler(http.StripPrefix(StaticAssetsURLPathPrefix, http.FileServer(http.Dir(staticAssetsPath))))
router.Path("/metrics").Handler(promhttp.Handler())
fmt.Println("Serving requests on port 9000")
err = http.ListenAndServe(":9000", router)
log.Fatal(err)
}