Skip to content

Commit ed9b0cc

Browse files
authored
Merge pull request #10 from practicalgo/publish_code
Publish chap7/abort-processing-timeout
2 parents abd9c83 + 73478c0 commit ed9b0cc

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
module github.com/practicalgo/code/chap7/abort-processing-timeout
2+
3+
go 1.16
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
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+
}

0 commit comments

Comments
 (0)