How to Build a Metrics Dashboard Backend in Go

Web
Build a Go metrics backend by creating an HTTP server with JSON endpoints using the net/http package.

Use the net/http package to create an HTTP server that exposes JSON endpoints for your metrics.

package main

import (
	"encoding/json"
	"net/http"
	"time"
)

type Metric struct {
	Name  string  `json:"name"`
	Value float64 `json:"value"`
	Time  time.Time `json:"time"`
}

var metrics []Metric

func getMetrics(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(metrics)
}

func main() {
	metrics = append(metrics, Metric{Name: "cpu_usage", Value: 45.2, Time: time.Now()})
	http.HandleFunc("/metrics", getMetrics)
	http.ListenAndServe(":8080", nil)
}