Created
January 15, 2022 19:50
-
-
Save 2hamed/7eb8e0270e7069341e97fd82714c047e to your computer and use it in GitHub Desktop.
This file contains hidden or 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" | |
"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