-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
101 lines (81 loc) · 2.41 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
package main
import (
"fmt"
"net/http"
"strconv"
"github.com/gorilla/mux"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/client_golang/prometheus/promhttp"
_ "github.com/kosha/teamwork-connector/docs"
"github.com/kosha/teamwork-connector/pkg/app"
"github.com/kosha/teamwork-connector/pkg/logger"
)
var (
log = logger.New("app", "teamwork-connector")
port = 8015
)
type responseWriter struct {
http.ResponseWriter
statusCode int
}
func NewResponseWriter(w http.ResponseWriter) *responseWriter {
return &responseWriter{w, http.StatusOK}
}
func (rw *responseWriter) WriteHeader(code int) {
rw.statusCode = code
rw.ResponseWriter.WriteHeader(code)
}
var totalRequests = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "http_requests_total",
Help: "Number of get requests.",
},
[]string{"path"},
)
var responseStatus = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "response_status",
Help: "Status of HTTP response",
},
[]string{"status"},
)
var httpDuration = promauto.NewHistogramVec(prometheus.HistogramOpts{
Name: "http_response_time_seconds",
Help: "Duration of HTTP requests.",
}, []string{"path"})
func prometheusMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
route := mux.CurrentRoute(r)
path, _ := route.GetPathTemplate()
timer := prometheus.NewTimer(httpDuration.WithLabelValues(path))
rw := NewResponseWriter(w)
next.ServeHTTP(rw, r)
statusCode := rw.statusCode
responseStatus.WithLabelValues(strconv.Itoa(statusCode)).Inc()
totalRequests.WithLabelValues(path).Inc()
timer.ObserveDuration()
})
}
func init() {
prometheus.Register(totalRequests)
prometheus.Register(responseStatus)
prometheus.Register(httpDuration)
}
// @title Teamwork Connector API
// @version 1.0
// @description This is a Kosha REST service for exposing many teamwork features as REST APIs with better consistency, observability etc
// @termsOfService http://swagger.io/terms/
// @contact.name API Support
// @contact.email [email protected]
// @host localhost:8015
// @BasePath /
func main() {
a := app.App{}
a.Initialize(log)
a.Router.Use(prometheusMiddleware)
// Prometheus metrics endpoint
a.Router.Path("/metrics").Handler(promhttp.Handler())
log.Infof("Running teamwork-connector on port %d", port)
a.Run(fmt.Sprintf(":%d", port))
}