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的更多相关文章

  1. Javascript 的执行环境(execution context)和作用域(scope)及垃圾回收

    执行环境有全局执行环境和函数执行环境之分,每次进入一个新执行环境,都会创建一个搜索变量和函数的作用域链.函数的局部环境不仅有权访问函数作用于中的变量,而且可以访问其外部环境,直到全局环境.全局执行环境 ...

  2. spring源码分析之<context:property-placeholder/>和<property-override/>

    在一个spring xml配置文件中,NamespaceHandler是DefaultBeanDefinitionDocumentReader用来处理自定义命名空间的基础接口.其层次结构如下: < ...

  3. spring源码分析之context

    重点类: 1.ApplicationContext是核心接口,它为一个应用提供了环境配置.当应用在运行时ApplicationContext是只读的,但你可以在该接口的实现中来支持reload功能. ...

  4. CSS——关于z-index及层叠上下文(stacking context)

    以下内容根据CSS规范翻译. z-index 'z-index'Value: auto | <integer> | inheritInitial: autoApplies to: posi ...

  5. Tomcat启动报错org.springframework.web.context.ContextLoaderListener类配置错误——SHH框架

    SHH框架工程,Tomcat启动报错org.springframework.web.context.ContextLoaderListener类配置错误 1.查看配置文件web.xml中是否配置.or ...

  6. mono for android Listview 里面按钮 view Button click 注册方法 并且传值给其他Activity 主要是context

    需求:为Listview的Item里面的按钮Button添加一个事件,单击按钮时通过事件传值并跳转到新的页面. 环境:mono 效果: 布局代码 主布局 <?xml version=" ...

  7. Javascript的“上下文”(context)

    一:JavaScript中的“上下文“指的是什么 百科中这样定义: 上下文是从英文context翻译过来,指的是一种环境. 在软件工程中,上下文是一种属性的有序序列,它们为驻留在环境内的对象定义环境. ...

  8. spring源码分析之<context:component-scan/>vs<annotation-config/>

    1.<context:annotation-config/> xsd中说明: <xsd:element name="annotation-config"> ...

  9. 【Android】 context.getSystemService()浅析

    同事在进行code review的时候问到我context中的getSystemService方法在哪实现的,他看到了一个ClipBoardManager来进行剪切板存储数据的工具方法中用到了cont ...

  10. context:component-scan" 的前缀 "context" 未绑定。

    SpElUtilTest.testSpELLiteralExpressiontestSpELLiteralExpression(cn.zr.spring.spel.SpElUtilTest)org.s ...

随机推荐

  1. No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK问题解决

    Maven构建项目报错: 解决办法: 1.eclipse菜单 -  Window - Preferences- Java - Installed JREs 将配置的JRE定位到JDK,例如JRE ho ...

  2. WMS工作原理

    图1:创建窗口 图2:通信过程 我们知道其实任何一个窗口的创建,最终都是会创建一个 ViewRootImpl对象.ViewRootImpl 是一很重要的类,类似 ActivityThread 负责跟A ...

  3. ie11的版本判断

    我的电脑昨天更新的时候把ie11给更新出来了,然后发现我的skylineweb项目提示我的浏览器不是ie,这样显然是浏览器检测出现了问题.查找后找到了下面的解决方法.大家的电脑如果也更新成了ie11的 ...

  4. ffmpeg 转码命令与ffplay

    ffmpeg.exe用于视频的转码. ▫ 最简单的命令 ffmpeg -i input.avi -b:v 640k output.ts 该命令将当前文件夹下的input.avi文件转换为output. ...

  5. PHP——判断数组中是否有重复值并找出重复值

    可以用来测试需要唯一凭据号码的,是否有重复值,不过一般直接使用uuid了,简单粗暴就解决问题,这个就简单的测试生成的数据是否有重复值吧 <?php /* * @Author: wyy * @Da ...

  6. Matplotlib学习---用seaborn画直方图,核密度图(histogram, kdeplot)

    由于直方图受组距(bin size)影响很大,设置不同的组距可能会产生完全不同的可视化结果.因此我们可以用密度平滑估计来更好地反映数据的真实特征.具体可参见这篇文章:https://blog.csdn ...

  7. 【XSY1522】灯 乱搞

    题目大意 ​ \(n\)盏灯排成一列,标号\(1\)到\(n\),一开始标号为\(1\)的灯亮着. ​ 现在依次对于\(2\)~\(n\)的每一个质数\(p_i\),指定一盏亮着的灯\(a_i\),点 ...

  8. Vijos P1459 车展 (treap 任意区间中位数)

    题面: 描述 遥控车是在是太漂亮了,韵韵的好朋友都想来参观,所以游乐园决定举办m次车展.车库里共有n辆车,从左到右依次编号为1,2,…,n,每辆车都有一个展台.刚开始每个展台都有一个唯一的高度h[i] ...

  9. hdu 5510 Bazinga (KMP+暴力标记)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5510 思路: 一开始直接用KMP莽了发,超时了,后面发现如果前面的字符串被后面的字符串包含,那么我们就 ...

  10. day2 网络基础

    网路基础 网络OSI模型七层: 物理层: 定义特性:机械,电器,功能,过程: 定义接口标准:双绞线,光纤,同轴电缆: 相关协议:无: 数据链路层: 定义帧的开始结束,封装成帧,差错校验,透明传输(防止 ...