File tree Expand file tree Collapse file tree 2 files changed +37
-0
lines changed
chap7/abort-processing-timeout Expand file tree Collapse file tree 2 files changed +37
-0
lines changed Original file line number Diff line number Diff line change 1+ module github.com/practicalgo/code/chap7/abort-processing-timeout
2+
3+ go 1.16
Original file line number Diff line number Diff line change 1+ package main
2+
3+ import (
4+ "fmt"
5+ "log"
6+ "net/http"
7+ "time"
8+ )
9+
10+ func handleUserAPI (w http.ResponseWriter , r * http.Request ) {
11+ log .Println ("I started processing the request" )
12+ time .Sleep (15 * time .Second )
13+
14+ log .Println ("Before continuing, i will check if the timeout has already expired" )
15+ if r .Context ().Err () != nil {
16+ log .Printf ("Aborting further processing: %v\n " , r .Context ().Err ())
17+ return
18+ }
19+ fmt .Fprintf (w , "Hello world!" )
20+ log .Println ("I finished processing the request" )
21+ }
22+
23+ func main () {
24+
25+ timeoutDuration := 14 * time .Second
26+
27+ userHandler := http .HandlerFunc (handleUserAPI )
28+ hTimeout := http .TimeoutHandler (userHandler , timeoutDuration , "I ran out of time" )
29+
30+ mux := http .NewServeMux ()
31+ mux .Handle ("/api/users/" , hTimeout )
32+
33+ log .Fatal (http .ListenAndServe (":8080" , mux ))
34+ }
You can’t perform that action at this time.
0 commit comments