about summary refs log tree commit diff
path: root/src/http.go
blob: 1ff432b10f6a86cb5ff5df2bce8db14fcbe1af69 (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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package main

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

	"github.com/gorilla/mux"
)

func setupHTTPServer(config config) {

	// start the http server logging the metrics
	log.Printf("Starting HTTP metrics listener on port %d", config.httpPort)

	r := mux.NewRouter()
	r.HandleFunc("/", indexHandler)
	r.HandleFunc("/metrics", metricsHandler)
	r.HandleFunc("/locations", locationHandlerEndpoint)

	// start the http server exposing the metrics and the locations
	httpPortString := fmt.Sprintf("%s:%d", config.bindIP, config.httpPort)
	listenErr := http.ListenAndServe(httpPortString, r)

	// handle potential errors
	if listenErr != nil {
		log.Fatalln(listenErr.Error())
	}
}

// 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)
	}
}