go context
Context 使用原则
1、不要把Context放在结构体中,要以参数的方式传递
2、以Context作为参数的函数方法,应该把Context作为第一个参数,放在第一位。
3、给一个函数方法传递Context的时候,不要传递nil,如果不知道传递什么,就使用context.TODO
4、Context的Value相关方法应该传递必须的数据,不要什么数据都使用这个传递
5、Context是线程安全的,可以放心的在多个goroutine中传递
context取值
package main import (
"context"
"fmt"
) func process(ctx context.Context) {
ret,ok := ctx.Value("trace_id").(int)
if !ok {
ret = 21342423
} fmt.Printf("ret:%d\n", ret) s , _ := ctx.Value("session").(string)
fmt.Printf("session:%s\n", s)
} func main() {
ctx := context.WithValue(context.Background(), "trace_id", 13483434)
ctx = context.WithValue(ctx, "session", "sdlkfjkaslfsalfsafjalskfj")
process(ctx)
}
结果

withcancel
package main import (
"context"
"fmt"
"time"
) func gen(ctx context.Context) <-chan int {
dst := make(chan int)
n := 1
go func() {
for {
select {
case <-ctx.Done():
fmt.Println("i exited")
return // returning not to leak the goroutine
case dst <- n:
n++
}
}
}()
return dst
} func test() {
// gen generates integers in a separate goroutine and
// sends them to the returned channel.
// The callers of gen need to cancel the context once
// they are done consuming generated integers not to leak
// the internal goroutine started by gen.
ctx, cancel := context.WithCancel(context.Background())
defer cancel() // cancel when we are finished consuming integers
intChan := gen(ctx)
for n := range intChan {
fmt.Println(n)
if n == 5 {
break
}
}
}
func main() {
test()
time.Sleep(time.Hour)
}
WithDeadline
package main import (
"context"
"fmt"
"time"
) func main() {
d := time.Now().Add(50 * time.Millisecond)
ctx, cancel := context.WithDeadline(context.Background(), d) // Even though ctx will be expired, it is good practice to call its
// cancelation function in any case. Failure to do so may keep the
// context and its parent alive longer than necessary.
defer cancel() select {
case <-time.After(1 * time.Second):
fmt.Println("overslept")
case <-ctx.Done():
fmt.Println(ctx.Err())
} }
go context的更多相关文章
- Javascript 的执行环境(execution context)和作用域(scope)及垃圾回收
执行环境有全局执行环境和函数执行环境之分,每次进入一个新执行环境,都会创建一个搜索变量和函数的作用域链.函数的局部环境不仅有权访问函数作用于中的变量,而且可以访问其外部环境,直到全局环境.全局执行环境 ...
- spring源码分析之<context:property-placeholder/>和<property-override/>
在一个spring xml配置文件中,NamespaceHandler是DefaultBeanDefinitionDocumentReader用来处理自定义命名空间的基础接口.其层次结构如下: < ...
- spring源码分析之context
重点类: 1.ApplicationContext是核心接口,它为一个应用提供了环境配置.当应用在运行时ApplicationContext是只读的,但你可以在该接口的实现中来支持reload功能. ...
- CSS——关于z-index及层叠上下文(stacking context)
以下内容根据CSS规范翻译. z-index 'z-index'Value: auto | <integer> | inheritInitial: autoApplies to: posi ...
- Tomcat启动报错org.springframework.web.context.ContextLoaderListener类配置错误——SHH框架
SHH框架工程,Tomcat启动报错org.springframework.web.context.ContextLoaderListener类配置错误 1.查看配置文件web.xml中是否配置.or ...
- mono for android Listview 里面按钮 view Button click 注册方法 并且传值给其他Activity 主要是context
需求:为Listview的Item里面的按钮Button添加一个事件,单击按钮时通过事件传值并跳转到新的页面. 环境:mono 效果: 布局代码 主布局 <?xml version=" ...
- Javascript的“上下文”(context)
一:JavaScript中的“上下文“指的是什么 百科中这样定义: 上下文是从英文context翻译过来,指的是一种环境. 在软件工程中,上下文是一种属性的有序序列,它们为驻留在环境内的对象定义环境. ...
- spring源码分析之<context:component-scan/>vs<annotation-config/>
1.<context:annotation-config/> xsd中说明: <xsd:element name="annotation-config"> ...
- 【Android】 context.getSystemService()浅析
同事在进行code review的时候问到我context中的getSystemService方法在哪实现的,他看到了一个ClipBoardManager来进行剪切板存储数据的工具方法中用到了cont ...
- context:component-scan" 的前缀 "context" 未绑定。
SpElUtilTest.testSpELLiteralExpressiontestSpELLiteralExpression(cn.zr.spring.spel.SpElUtilTest)org.s ...
随机推荐
- codeforces707C
Pythagorean Triples CodeForces - 707C 悉宇大大最近在学习三角形和勾股定理.很显然,你可以用三个边长为正数的线段去构造一个直角三角形,而这三个数被称作“勾股数”. ...
- Civil 3d设置横断面图样式
一位网友提出这样一个问题: 在使用SectionView.StyleName属性时, 会抛出异常:need to override property StyleName. 我测试的结果一样, 同时测试 ...
- webpack 打包编译-webkit-box-orient: vertical 后消失
/* autoprefixer: off */ -webkit-box-orient: vertical; // 参考 https://github.com/postcss/autoprefixer/ ...
- JS操作Cookies
JS操作Cookies 获取Cookie function getCookie(c_name) { if (document.cookie.length > 0) { c_start = doc ...
- veu——引入iconfont图标
我这里是阿里的iconfont图标,如何下载请看下面这个博文 https://www.cnblogs.com/wangyang0210/articles/9248324.html 创建文件夹 在ass ...
- JMeter——JMeter如何进行汉化
1.找到bin目录下的jmeter.properties文件 2.打开找到第37行,打开注释并将language=en改为language=zh_CN 3.重启
- 第五十五天 css基础入门
一.引入css的三种方式 1.行间式 <div style="width: 100px; height: 100px; background-color: red">& ...
- HUST 1555 数学作业
参考自:https://www.cnblogs.com/ECJTUACM-873284962/p/6394892.html 1555 - A Math Homework 时间限制:1秒 内存限制:12 ...
- BZOJ4653 [NOI2016] 区间 【线段树】
题目分析: 首先思考一个二分答案的做法.我们可以注意到答案具有单调性,所以可以二分答案. 假设当前二分的答案是$ k $.那么按照大小顺序插入每个区间,同时在末端删除会对答案产生影响的区间.这里不妨用 ...
- 【XSY1522】灯 乱搞
题目大意 \(n\)盏灯排成一列,标号\(1\)到\(n\),一开始标号为\(1\)的灯亮着. 现在依次对于\(2\)~\(n\)的每一个质数\(p_i\),指定一盏亮着的灯\(a_i\),点 ...