-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathcontext_test.go
54 lines (42 loc) · 958 Bytes
/
context_test.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
package contexts
import (
"context"
"fmt"
"net/http"
"testing"
"time"
)
func TestContext(t *testing.T) {
go func() {
cContext()
}()
time.Sleep(time.Second)
reqest, _ := http.NewRequest("GET", "http://localhost:8099/hello", nil) // http client get 请求
client := &http.Client{}
ctx, cancel := context.WithCancel(context.Background())
reqest = reqest.WithContext(ctx)
go func() {
select {
case <-time.After(2 * time.Second):
cancel()
}
}()
client.Do(reqest)
}
func hello(w http.ResponseWriter, req *http.Request) {
ctx := req.Context()
defer fmt.Println("server: hello handler ended")
select {
case <-time.After(10 * time.Second):
fmt.Fprintf(w, "hello\n")
case <-ctx.Done():
err := ctx.Err()
fmt.Println("server:", err)
internalError := http.StatusInternalServerError
http.Error(w, err.Error(), internalError)
}
}
func cContext() {
http.HandleFunc("/hello", hello)
http.ListenAndServe(":8099", nil)
}