about summary refs log tree commit diff
path: root/src/http.go
blob: 47f0d75b41321ad37bebb862e12531a69c7c6c67 (plain)
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
package main

import (
	"fmt"
	"net/http"
	"strings"
)

// locationHandlerEndpoint handles requests to the /locations endpoint
// This is used by the grafana worldmap plugin to find out where to draw the
// fancy circles
func locationHandlerEndpoint(w http.ResponseWriter, r *http.Request) {

	// set some headers
	w.Header().Set("Content-Type", "application/json")
	w.Header().Set("Access-Control-Allow-Origin", "https://grafana.nbg1.emile.space")

	// start building json (yes, this is not a nice implementation, PRs welcome!)
	fmt.Fprintf(w, "%s", "[")

	var i int = 0
	for _, v := range cities {

		// print the "json" object containing the metrics needed
		fmt.Fprintf(w, "{")
		fmt.Fprintf(w, "\"key\": \"%s\",", v.key)
		fmt.Fprintf(w, "\"latitude\": %f,", v.latitude)
		fmt.Fprintf(w, "\"longitude\": %f,", v.longitude)
		fmt.Fprintf(w, "\"name\": \"%s\"", v.name)

		// close the object (this handles the trailing comma problem)
		if i == len(cities)-1 {
			fmt.Fprintf(w, "}")
		} else {
			fmt.Fprintf(w, "},")
		}
		i++
	}
	fmt.Fprintf(w, "%s", "]")
}

// indexHandler handles the request to the / endpoint
// It simply returns a link to the /metrics page
func indexHandler(w http.ResponseWriter, req *http.Request) {
	_, _ = fmt.Fprintf(w, "<a href='/metrics'>metrics</a>")
}

// Handle HTTP requests to the /metrics endpoint
func metricsHandler(w http.ResponseWriter, req *http.Request) {

	// return the overall amount of passwords catched
	fmt.Fprintf(w, "num_passwords %d\n", metricsNumPasswords)

	// return the amount of passwords catched from a given city
	for k, v := range metricsCityNum {
		fmt.Fprintf(w, "a_metric{city=\"%s\"} %d\n", strings.ToLower(k), v)
	}
}