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
  | 
package main
import (
	"flag"
	"fmt"
	"github.com/gorilla/mux"
	"log"
	"net/http"
	"strconv"
)
var (
	metrics map[string]float64
)
func metricsHandler(w http.ResponseWriter, r *http.Request) {
	// if the request method is GET, return all metrics
	if r.Method == "GET" {
		// if the length of the metrics map is zero, return some information on how to add metrics
		if len(metrics) == 0 {
			returnString := "Add metrics by making a post request to this endpoint\n" +
				"curl -X POST --data = \"\" <url>:<port>/meetrics"
			_, _ = fmt.Fprintf(w, returnString)
		} else {
			// return all the metrics
			for key, value := range metrics {
				_, _ = fmt.Fprintf(w, "%s %f\n", key, value)
			}
		}
		// if the request method is POST, add the posted metrics to the metrics map
	} else if r.Method == "POST" {
		// parse the POST form
		errParseForm := r.ParseForm()
		if errParseForm != nil {
			panic(errParseForm)
		}
		// parse the parameters
		key := r.Form.Get("key")
		value, parseFloatErr := strconv.ParseFloat(r.Form.Get("value"), 64)
		if parseFloatErr != nil {
			log.Printf("Error parsing %v", value)
		}
		// if the metrics var does not exist yet, create it
		if metrics == nil {
			metrics = map[string]float64{}
		}
		// assign the value to the key
		metrics[key] = value
		_, _ = fmt.Fprintf(w, "added the metrics")
		// return an error
	} else {
		log.Println("Error, the handler was neither accessed using a GET or a POST request!")
	}
}
func main() {
	// parse some command line flags
	var port string
	flag.StringVar(&port, "p", "8080", "port used to host the service")
	flag.Parse()
	log.Println("[ ] Done loading the flags")
	// setup a new router and define routes
	r := mux.NewRouter()
	r.HandleFunc("/metrics", metricsHandler).Methods("GET", "POST")
	// start the http server
	log.Printf("Starting the http server on port %s", port)
	log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), r))
}
 
  |