diff options
-rw-r--r-- | main.go | 84 |
1 files changed, 84 insertions, 0 deletions
diff --git a/main.go b/main.go new file mode 100644 index 0000000..32e572b --- /dev/null +++ b/main.go @@ -0,0 +1,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)) +} |