func requestCtrMiddleware(next httpctx.Handler) httpctx.Handler { return httpctx.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) { counter.Incr(1) hitsperminute.Set(counter.Rate()) next.ServeHTTP(ctx, w, r) }) }
func userIPMiddleware(next httpctx.Handler) httpctx.Handler { return httpctx.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) { if userIP, ok := userip.FromRequest(r); ok == nil { ctx = userip.NewContext(ctx, userIP) } next.ServeHTTP(ctx, w, r) }) }
func requestIDMiddleware(next httpctx.Handler) httpctx.Handler { return httpctx.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) { if reqID, ok := requestid.FromRequest(r); ok == nil { ctx = requestid.NewContext(ctx, reqID) } next.ServeHTTP(ctx, w, r) }) }
func main() { counter = ratecounter.NewRateCounter(1 * time.Minute) port := os.Getenv("PORT") if port == "" { log.Fatal("$PORT must be set") } var handler httpctx.Handler handler = httpctx.HandlerFunc(requestHandler) handler = userIPMiddleware(handler) handler = requestIDMiddleware(handler) handler = requestCtrMiddleware(handler) ctx := context.Background() svc := &Server{ctx, handler} http.HandleFunc("/", svc.ServeHTTP) log.Fatal(http.ListenAndServe(":"+port, nil)) }