From 73478c099afc2f256b97068f4c57e67a87229437 Mon Sep 17 00:00:00 2001 From: Amit Saha Date: Thu, 1 Sep 2022 06:28:17 +1000 Subject: [PATCH] Publish chap7/abort-processing-timeout --- chap7/abort-processing-timeout/go.mod | 3 +++ chap7/abort-processing-timeout/server.go | 34 ++++++++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 chap7/abort-processing-timeout/go.mod create mode 100644 chap7/abort-processing-timeout/server.go diff --git a/chap7/abort-processing-timeout/go.mod b/chap7/abort-processing-timeout/go.mod new file mode 100644 index 0000000..f6d5c57 --- /dev/null +++ b/chap7/abort-processing-timeout/go.mod @@ -0,0 +1,3 @@ +module github.com/practicalgo/code/chap7/abort-processing-timeout + +go 1.16 diff --git a/chap7/abort-processing-timeout/server.go b/chap7/abort-processing-timeout/server.go new file mode 100644 index 0000000..5b624f1 --- /dev/null +++ b/chap7/abort-processing-timeout/server.go @@ -0,0 +1,34 @@ +package main + +import ( + "fmt" + "log" + "net/http" + "time" +) + +func handleUserAPI(w http.ResponseWriter, r *http.Request) { + log.Println("I started processing the request") + time.Sleep(15 * time.Second) + + log.Println("Before continuing, i will check if the timeout has already expired") + if r.Context().Err() != nil { + log.Printf("Aborting further processing: %v\n", r.Context().Err()) + return + } + fmt.Fprintf(w, "Hello world!") + log.Println("I finished processing the request") +} + +func main() { + + timeoutDuration := 14 * time.Second + + userHandler := http.HandlerFunc(handleUserAPI) + hTimeout := http.TimeoutHandler(userHandler, timeoutDuration, "I ran out of time") + + mux := http.NewServeMux() + mux.Handle("/api/users/", hTimeout) + + log.Fatal(http.ListenAndServe(":8080", mux)) +}