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, "metrics") } // 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) } }