-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
107 lines (87 loc) · 2.5 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package main
import (
"context"
"encoding/json"
"io"
"net/http"
"time"
)
/*
What is done here?
- Used a API using beeceptor to simulate timeouts
- Create Timeout Handlers which make the request to the above API. If the response is not received in the specified duration, it times out.
Else it returns proper response.
- Created the same function as above but put all in one function and took timeout from query
*/
type TimeoutHandler struct {
dt time.Duration
hdlr func(w http.ResponseWriter, r *http.Request)
}
func (h *TimeoutHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx, cf := context.WithTimeout(r.Context(), h.dt)
defer cf()
done := make(chan struct{})
go func() {
h.hdlr(w, r)
done <- struct{}{}
}()
select {
case <-done:
return
case <-ctx.Done():
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusRequestTimeout)
en := json.NewEncoder(w)
en.Encode(map[string]string{"err": "request timeout"})
}
}
func Timeout(dt time.Duration, hdlr func(w http.ResponseWriter, r *http.Request)) TimeoutHandler {
return TimeoutHandler{dt, hdlr}
}
func SimpleTimeout(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
dt, err := time.ParseDuration(q.Get("timeout"))
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
ctx, cl := context.WithTimeout(r.Context(), dt)
defer cl()
done := make(chan struct{})
go func() {
res, _ := http.Get("https://asdfg.free.beeceptor.com/delay")
w.Header().Set("Content-Type", "application/json")
x, _ := io.ReadAll(res.Body)
w.Write(x)
close(done)
}()
select {
case <-done:
return
case <-ctx.Done():
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusRequestTimeout)
en := json.NewEncoder(w)
en.Encode(map[string]string{"err": "request timeout"})
}
}
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
en := json.NewEncoder(w)
en.Encode(map[string]string{"success": "1"})
})
delayFunc := func(w http.ResponseWriter, r *http.Request) {
res, _ := http.Get("https://asdfg.free.beeceptor.com/delay")
w.Header().Set("Content-Type", "application/json")
x, _ := io.ReadAll(res.Body)
w.Write(x)
}
timeoutFunc := Timeout(1*time.Second, delayFunc)
http.HandleFunc("/timeout", timeoutFunc.ServeHTTP)
http.HandleFunc("/delay", SimpleTimeout)
if err := http.ListenAndServe(":8888", nil); err != nil {
panic(err)
}
}