当前位置:网站首页>Usage scenarios of golang context
Usage scenarios of golang context
2022-07-05 06:12:00 【Dawnlighttt】
List of articles
1. Value passed
Value passing is just context An auxiliary function of , Not the core function . Usually we only use context To pass optional data that does not affect the main business logic , Like log information 、 Debugging information, meta information, etc .
package main
import (
"context"
"fmt"
)
func readContext(ctx context.Context) {
traceId, ok := ctx.Value("key").(string)
if ok {
fmt.Println("readContext key=", traceId)i
} else {
fmt.Println("readContext no key")
}
}
func main() {
ctx := context.Background()
readContext(ctx)
ctx = context.WithValue(ctx, "key", "beautiful")
readContext(ctx)
}
In the use of WithValue Yes ctx When packing , You can set a key-value Key value pair , stay goroutine Passed between .
2. Timeout control
http Request to set timeout
package main
import (
"context"
"fmt"
"time"
)
func httpRequest(ctx context.Context) {
for {
// Handle http request
select {
case <- ctx.Done():
fmt.Println("Request timed out")
return
case <- time.After(time.Second):
fmt.Println("Loading...")
}
}
}
func main() {
fmt.Println("start TestTimeoutContext")
ctx, cancel := context.WithTimeout(context.Background(), time.Second * 3)
defer cancel()
httpRequest(ctx)
time.Sleep(time.Second * 5)
}
//start TestTimeoutContext
//Loading...
//Loading...
//Request timed out
file io Or the Internet io Wait for time-consuming operations , You can check whether the remaining time is sufficient , Decide whether to proceed to the next step
package main
import (
"context"
"fmt"
"time"
)
func copyFile(ctx context.Context) {
deadline, ok := ctx.Deadline()
if ok == false {
return
}
// deadline.Sub(time.Now()) The difference between the deadline and the current time
isEnough := deadline.Sub(time.Now()) > time.Second * 5
if isEnough {
fmt.Println("copy file")
} else {
fmt.Println("isEnough is false return")
return
}
}
func main() {
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Second * 4))
defer cancel()
copyFile(ctx)
time.Sleep(time.Second * 5)
}
//isEnough is false return
3. Cancel control
goroutine Send a cancellation signal , Ensure that the logic emanates from yourself goroutine All cancelled successfully
package main
import (
"context"
"fmt"
"time"
)
func gen(ctx context.Context) <-chan int {
ch := make(chan int)
go func() {
var n int
for {
select {
case ch <- n:
n++
time.Sleep(time.Second)
case <-ctx.Done():
return
}
}
}()
return ch
}
func main() {
// Create a Cancel context
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
for n := range gen(ctx) {
fmt.Println(n)
if n == 5 {
// Trigger after meeting the requirements cancel
cancel()
break
}
}
}
//0
//1
//2
//3
//4
//5
Reference material :
边栏推荐
- JS quickly converts JSON data into URL parameters
- Daily question 2013 Detect square
- Basic explanation of typescript
- Daily question 1688 Number of matches in the competition
- 【Rust 笔记】16-输入与输出(上)
- LeetCode 1200.最小绝对差
- wordpress切换页面,域名变回了IP地址
- Open source storage is so popular, why do we insist on self-development?
- 【Rust 笔记】15-字符串与文本(上)
- 【Rust 笔记】14-集合(下)
猜你喜欢

Some common problems in the assessment of network engineers: WLAN, BGP, switch

Solution to game 10 of the personal field

wordpress切换页面,域名变回了IP地址

Leetcode-6110: number of incremental paths in the grid graph

传统数据库逐渐“难适应”,云原生数据库脱颖而出

Scope of inline symbol

做 SQL 性能优化真是让人干瞪眼

数据可视化图表总结(二)

Wazuh開源主機安全解决方案的簡介與使用體驗

QQ computer version cancels escape character input expression
随机推荐
R language [import and export of dataset]
QQ computer version cancels escape character input expression
Simple knapsack, queue and stack with deque
[jailhouse article] jailhouse hypervisor
1039 Course List for Student
Full Permutation Code (recursive writing)
【Rust 笔记】16-输入与输出(上)
Common optimization methods
Dichotomy, discretization, etc
6. Logistic model
【Rust 笔记】15-字符串与文本(下)
Shutter web hardware keyboard monitoring
Control unit
Spark中groupByKey() 和 reduceByKey() 和combineByKey()
js快速将json数据转换为url参数
LVS简介【暂未完成(半成品)】
leetcode-556:下一个更大元素 III
In depth analysis of for (VaR I = 0; I < 5; i++) {settimeout (() => console.log (I), 1000)}
开源存储这么香,为何我们还要坚持自研?
【Rust 笔记】17-并发(上)