-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
226 lines (184 loc) · 5.38 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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
package main
import (
"os"
// "os/signal"
// "syscall"
"fmt"
"log"
"time"
"strings"
"strconv"
"net/http"
"database/sql"
_ "github.com/mattn/go-sqlite3"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/gorilla/mux"
)
var storage = getenv("STORAGE", "file")
func checkErr(err error) {
if err != nil {
log.Fatal(err.Error())
}
}
func getenv(key, fallback string) string {
value := os.Getenv(key)
if len(value) == 0 {
return fallback
}
return value
}
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{"code", "path", "method"},
)
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()
method := r.Method
timer := prometheus.NewTimer(httpDuration.WithLabelValues(path))
rw := NewResponseWriter(w)
next.ServeHTTP(rw, r)
statusCode := rw.statusCode
responseStatus.WithLabelValues(strconv.Itoa(statusCode)).Inc()
totalRequests.WithLabelValues(strconv.Itoa(statusCode), path, method).Inc()
timer.ObserveDuration()
})
}
func init() {
prometheus.Register(totalRequests)
prometheus.Register(responseStatus)
prometheus.Register(httpDuration)
}
func main() {
router := mux.NewRouter()
router.Use(prometheusMiddleware)
router.HandleFunc("/hello", HelloPage).Methods("GET")
router.HandleFunc("/", HelloServer).Methods("GET")
router.HandleFunc("/user", LogAccess).Methods("GET", "POST")
router.Handle("/metrics", promhttp.Handler()).Methods("GET")
http.ListenAndServe(":8080", router)
}
func Metrics(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %s!", r.URL.Path[1:])
}
func HelloServer(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %s!", r.URL.Path[1:])
}
func HelloPage(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
w.WriteHeader(http.StatusOK)
log.Printf("Display hello-page")
fmt.Fprintf(w, "Hello Page")
return
}
log.Printf("Client used wrong method")
w.WriteHeader(http.StatusMethodNotAllowed)
}
func LogAccess(w http.ResponseWriter, r *http.Request) {
if storage == "file" {
if r.Method == "POST" {
name := r.FormValue("name")
if name == "" {
w.WriteHeader(http.StatusExpectationFailed)
fmt.Fprintf(w, "name not defined")
}
file, err := os.OpenFile("db.txt", os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
panic(err)
}
defer file.Close()
_, err2 := file.WriteString(fmt.Sprintf("%v,%v\n", name, time.Now().Format(time.RFC3339)))
if err2 != nil {
log.Fatal(err2)
}
w.WriteHeader(http.StatusOK)
log.Printf("Add '" + name + "' to journal")
return
}
w.WriteHeader(http.StatusNotImplemented)
}
if storage == "sql" {
user := r.FormValue("name")
database, err := sql.Open("sqlite3", "./db.sql")
checkErr(err)
defer database.Close()
createTable(database)
if r.Method == "GET" {
timestamps := showTimestamps(database, user)
fmt.Fprintf(w, strings.Join(timestamps, "\n"))
log.Printf("Show log")
return
}
if r.Method == "POST" {
insertRow(database, user, time.Now().Format(time.RFC3339))
w.WriteHeader(http.StatusOK)
log.Printf("Add '" + user + "' to journal")
return
}
w.WriteHeader(http.StatusNotImplemented)
}
}
func insertRow(db *sql.DB, user string, timestamp string) {
log.Println("Inserting record ...")
insertRowSQL := `INSERT INTO users (user, timestamp) values (?, ?)`
statement, err := db.Prepare(insertRowSQL)
checkErr(err)
// This is good to avoid SQL injections
_, err = statement.Exec(user, timestamp)
checkErr(err)
}
func showTimestamps(db *sql.DB, u string) []string {
rows, err := db.Query("SELECT id, user, timestamp FROM users WHERE user IS ?", u)
checkErr(err)
defer rows.Close()
timestamps := make([]string, 0)
var id int
var user string
var timestamp string
for rows.Next() {
rows.Scan(&id, &user, ×tamp)
timestamps = append(timestamps, timestamp)
log.Printf("Got row: " + strconv.Itoa(id))
}
return timestamps
}
func createTable(db *sql.DB) {
createTableSQL := `CREATE TABLE IF NOT EXISTS users (
"id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
"user" TEXT,
"timestamp" TEXT
);`
log.Println("Creating table...")
statement, err := db.Prepare(createTableSQL)
checkErr(err)
statement.Exec()
log.Println("Table created")
}