当前位置:网站首页>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 :
边栏推荐
- LeetCode 1200. Minimum absolute difference
- 2022年贵州省职业院校技能大赛中职组网络安全赛项规程
- 2022 极术通讯-Arm 虚拟硬件加速物联网软件开发
- [rust notes] 17 concurrent (Part 1)
- A reason that is easy to be ignored when the printer is offline
- Implement a fixed capacity stack
- 【Rust 笔记】16-输入与输出(下)
- 1.14 - assembly line
- 1039 Course List for Student
- The sum of the unique elements of the daily question
猜你喜欢

On the characteristics of technology entrepreneurs from Dijkstra's Turing Award speech

Doing SQL performance optimization is really eye-catching

MIT-6874-Deep Learning in the Life Sciences Week 7

redis发布订阅命令行实现

LeetCode 0107. Sequence traversal of binary tree II - another method

Typical use cases for knapsacks, queues, and stacks

MatrixDB v4.5.0 重磅发布,全新推出 MARS2 存储引擎!

Implement a fixed capacity stack

API related to TCP connection

LaMDA 不可能觉醒吗?
随机推荐
1.14 - 流水线
How to adjust bugs in general projects ----- take you through the whole process by hand
Implement an iterative stack
【Rust 笔记】15-字符串与文本(上)
“磐云杯”中职网络安全技能大赛A模块新题
In depth analysis of for (VaR I = 0; I < 5; i++) {settimeout (() => console.log (I), 1000)}
Spark中groupByKey() 和 reduceByKey() 和combineByKey()
Règlement sur la sécurité des réseaux dans les écoles professionnelles secondaires du concours de compétences des écoles professionnelles de la province de Guizhou en 2022
Analysis of backdoor vulnerability in remote code execution penetration test / / phpstudy of national game title of national secondary vocational network security B module
Navicat連接Oracle數據庫報錯ORA-28547或ORA-03135
liunx启动redis
R language [import and export of dataset]
Convolution neural network -- convolution layer
做 SQL 性能优化真是让人干瞪眼
Introduction to LVS [unfinished (semi-finished products)]
【Rust 笔记】14-集合(上)
leetcode-3:无重复字符的最长子串
MIT-6874-Deep Learning in the Life Sciences Week 7
Quickly use Amazon memorydb and build your own redis memory database
Sqlmap tutorial (II) practical skills I