Created
August 6, 2020 08:02
-
-
Save cruisemaniac/cbf61ada9a9b4bb1efaff9916d4c35ca to your computer and use it in GitHub Desktop.
Golang Prometheus integration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"fmt" | |
"log" | |
"net/http" | |
"os" | |
"os/signal" | |
"syscall" | |
"time" | |
"github.com/gorilla/mux" | |
"github.com/prometheus/client_golang/prometheus" | |
"github.com/prometheus/client_golang/prometheus/promauto" | |
"github.com/prometheus/client_golang/prometheus/promhttp" | |
) | |
func recordMetrics() { | |
go func() { | |
opsProcessed.Inc() | |
}() | |
} | |
var ( | |
opsProcessed = promauto.NewCounter(prometheus.CounterOpts{ | |
Name: "go_hello_world_processed_ops_total", | |
Help: "The total number of processed events", | |
}) | |
) | |
func handler(w http.ResponseWriter, r *http.Request) { | |
query := r.URL.Query() | |
name := query.Get("name") | |
if name == "" { | |
name = "Guest" | |
} | |
log.Printf("Received request for %s\n", name) | |
w.Write([]byte(fmt.Sprintf("Hello, %s\n", name))) | |
recordMetrics() | |
} | |
func healthHandler(w http.ResponseWriter, r *http.Request) { | |
w.WriteHeader(http.StatusOK) | |
} | |
func readinessHandler(w http.ResponseWriter, r *http.Request) { | |
w.WriteHeader(http.StatusOK) | |
} | |
func main() { | |
r := mux.NewRouter() | |
r.HandleFunc("/", handler) | |
r.HandleFunc("/health", healthHandler) | |
r.HandleFunc("/readiness", readinessHandler) | |
r.Handle("/metrics", promhttp.Handler()) | |
srv := &http.Server{ | |
Handler: r, | |
Addr: ":8080", | |
ReadTimeout: 10 * time.Second, | |
WriteTimeout: 10 * time.Second, | |
} | |
go func() { | |
log.Println("Starting Server") | |
if err := srv.ListenAndServe(); err != nil { | |
log.Fatal(err) | |
} | |
}() | |
waitForShutdown(srv) | |
} | |
func waitForShutdown(srv *http.Server) { | |
interruptChan := make(chan os.Signal, 1) | |
signal.Notify(interruptChan, os.Interrupt, syscall.SIGINT, syscall.SIGTERM) | |
<-interruptChan | |
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) | |
defer cancel() | |
srv.Shutdown(ctx) | |
log.Println("Shutting down") | |
os.Exit(0) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment