Skip to content

Commit c334f8a

Browse files
committed
update readme
1 parent 6227d90 commit c334f8a

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

README.md

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ func call1(ctx context.Context) {
1717
call2(context.Background()) // Non-inherited new context, use function like `context.WithXXX` instead
1818

1919
call3() // Function `call3` should pass the context parameter
20+
call4() // Function `call4->call3` should pass the context parameter
2021
...
2122
}
2223

@@ -29,10 +30,68 @@ func call3() {
2930
call2(ctx)
3031
}
3132

33+
func call4() {
34+
call3()
35+
}
36+
37+
38+
// if you want none-inherit ctx, use this function
3239
func getNewCtx(ctx context.Context) (newCtx context.Context) {
3340
...
3441
return
3542
}
43+
44+
/* ---------- check net/http.HandleFunc ---------- */
45+
46+
func call5(ctx context.Context, w http.ResponseWriter, r *http.Request) {
47+
}
48+
49+
func call6(w http.ResponseWriter, r *http.Request) {
50+
ctx := r.Context()
51+
call5(ctx, w, r)
52+
call5(context.Background(), w, r) // Non-inherited new context, use function like `context.WithXXX` or `r.Context` instead
53+
}
54+
55+
func call7(in bool, w http.ResponseWriter, r *http.Request) {
56+
call5(r.Context(), w, r)
57+
call5(context.Background(), w, r)
58+
}
59+
60+
func call8() {
61+
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
62+
call5(r.Context(), w, r)
63+
call5(context.Background(), w, r) // Non-inherited new context, use function like `context.WithXXX` or `r.Context` instead
64+
65+
call6(w, r)
66+
67+
// call7 should be like `func call7(ctx context.Context, in bool, w http.ResponseWriter, r *http.Request)`
68+
call7(true, w, r) // Function `call7` should pass the context parameter
69+
})
70+
}
71+
```
72+
73+
## Tips
74+
75+
You can break ctx inheritance by this way, eg: [issue](https://github.com/sylvia7788/contextcheck/issues/2).
76+
77+
```go
78+
func call1(ctx context.Context) {
79+
...
80+
81+
newCtx, cancel := NoInheritCancel(ctx)
82+
defer cancel()
83+
84+
call2(newCtx)
85+
...
86+
}
87+
88+
func call2(ctx context.Context) {
89+
...
90+
}
91+
92+
func NoInheritCancel(_ context.Context) (context.Context,context.CancelFunc) {
93+
return context.WithCancel(context.Background())
94+
}
3695
```
3796

3897
## Installation

0 commit comments

Comments
 (0)