Skip to content

Instantly share code, notes, and snippets.

@2hamed
Created January 15, 2022 19:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 2hamed/7eb8e0270e7069341e97fd82714c047e to your computer and use it in GitHub Desktop.
Save 2hamed/7eb8e0270e7069341e97fd82714c047e to your computer and use it in GitHub Desktop.
package main
import (
"context"
"fmt"
"net/http"
"time"
"github.com/felixge/httpsnoop"
"github.com/go-chi/chi"
)
func main() {
r := chi.NewRouter()
r.With(middleware).Get("/", root)
http.ListenAndServe(":8080", r)
}
func root(w http.ResponseWriter, r *http.Request) {
err := longRun(r.Context())
if err != nil {
fmt.Println("error:", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(200)
}
func longRun(ctx context.Context) error {
c := make(chan bool)
go func() {
time.Sleep(3 * time.Minute)
c <- true
}()
select {
case <-ctx.Done():
return ctx.Err()
case <-c:
return nil
}
}
func middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
m := httpsnoop.CaptureMetrics(next, w, r)
fmt.Println("metrics: ", m)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment