亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

ディレクトリ 検索
archive archive/tar archive/zip bufio bufio(緩存) builtin builtin(內(nèi)置包) bytes bytes(包字節(jié)) compress compress/bzip2(壓縮/bzip2) compress/flate(壓縮/flate) compress/gzip(壓縮/gzip) compress/lzw(壓縮/lzw) compress/zlib(壓縮/zlib) container container/heap(容器數(shù)據(jù)結(jié)構(gòu)heap) container/list(容器數(shù)據(jù)結(jié)構(gòu)list) container/ring(容器數(shù)據(jù)結(jié)構(gòu)ring) context context(上下文) crypto crypto(加密) crypto/aes(加密/aes) crypto/cipher(加密/cipher) crypto/des(加密/des) crypto/dsa(加密/dsa) crypto/ecdsa(加密/ecdsa) crypto/elliptic(加密/elliptic) crypto/hmac(加密/hmac) crypto/md5(加密/md5) crypto/rand(加密/rand) crypto/rc4(加密/rc4) crypto/rsa(加密/rsa) crypto/sha1(加密/sha1) crypto/sha256(加密/sha256) crypto/sha512(加密/sha512) crypto/subtle(加密/subtle) crypto/tls(加密/tls) crypto/x509(加密/x509) crypto/x509/pkix(加密/x509/pkix) database database/sql(數(shù)據(jù)庫/sql) database/sql/driver(數(shù)據(jù)庫/sql/driver) debug debug/dwarf(調(diào)試/dwarf) debug/elf(調(diào)試/elf) debug/gosym(調(diào)試/gosym) debug/macho(調(diào)試/macho) debug/pe(調(diào)試/pe) debug/plan9obj(調(diào)試/plan9obj) encoding encoding(編碼) encoding/ascii85(編碼/ascii85) encoding/asn1(編碼/asn1) encoding/base32(編碼/base32) encoding/base64(編碼/base64) encoding/binary(編碼/binary) encoding/csv(編碼/csv) encoding/gob(編碼/gob) encoding/hex(編碼/hex) encoding/json(編碼/json) encoding/pem(編碼/pem) encoding/xml(編碼/xml) errors errors(錯(cuò)誤) expvar expvar flag flag(命令行參數(shù)解析flag包) fmt fmt go go/ast(抽象語法樹) go/build go/constant(常量) go/doc(文檔) go/format(格式) go/importer go/parser go/printer go/scanner(掃描儀) go/token(令牌) go/types(類型) hash hash(散列) hash/adler32 hash/crc32 hash/crc64 hash/fnv html html html/template(模板) image image(圖像) image/color(顏色) image/color/palette(調(diào)色板) image/draw(繪圖) image/gif image/jpeg image/png index index/suffixarray io io io/ioutil log log log/syslog(日志系統(tǒng)) math math math/big math/big math/bits math/bits math/cmplx math/cmplx math/rand math/rand mime mime mime/multipart(多部分) mime/quotedprintable net net net/http net/http net/http/cgi net/http/cookiejar net/http/fcgi net/http/httptest net/http/httptrace net/http/httputil net/http/internal net/http/pprof net/mail net/mail net/rpc net/rpc net/rpc/jsonrpc net/smtp net/smtp net/textproto net/textproto net/url net/url os os os/exec os/signal os/user path path path/filepath(文件路徑) plugin plugin(插件) reflect reflect(反射) regexp regexp(正則表達(dá)式) regexp/syntax runtime runtime(運(yùn)行時(shí)) runtime/debug(調(diào)試) runtime/internal/sys runtime/pprof runtime/race(競爭) runtime/trace(執(zhí)行追蹤器) sort sort(排序算法) strconv strconv(轉(zhuǎn)換) strings strings(字符串) sync sync(同步) sync/atomic(原子操作) syscall syscall(系統(tǒng)調(diào)用) testing testing(測(cè)試) testing/iotest testing/quick text text/scanner(掃描文本) text/tabwriter text/template(定義模板) text/template/parse time time(時(shí)間戳) unicode unicode unicode/utf16 unicode/utf8 unsafe unsafe
テキスト

  • import "context"

  • 概述

  • 索引

  • 示例

概述

Context 包定義了上下文類型,該上下文類型跨越 API 邊界和進(jìn)程之間傳遞截止期限,取消信號(hào)和其他請(qǐng)求范圍值。

對(duì)服務(wù)器的傳入請(qǐng)求應(yīng)創(chuàng)建一個(gè) Context,對(duì)服務(wù)器的傳出調(diào)用應(yīng)接受 Context。它們之間的函數(shù)調(diào)用鏈必須傳播 Context,可以用使用 WithCancel,WithDeadline,WithTimeout 或WithValue創(chuàng)建的派生上下文替換。當(dāng) Context 被取消時(shí),從它派生的所有 Context 也被取消。

WithCancel,WithDeadline 和 WithTimeout 函數(shù)采用Context(父級(jí))并返回派生的Context(子級(jí))和CancelFunc。調(diào)用 CancelFunc 將取消子對(duì)象及其子對(duì)象,刪除父對(duì)子對(duì)象的引用,并停止任何關(guān)聯(lián)的定時(shí)器。未能調(diào)用CancelFunc 會(huì)泄漏子項(xiàng)及其子項(xiàng),直至父項(xiàng)被取消或計(jì)時(shí)器激發(fā)。go vet 工具檢查在所有控制流路徑上使用 CancelFuncs。

使用 Contexts 的程序應(yīng)該遵循這些規(guī)則來保持包之間的接口一致,并使靜態(tài)分析工具能夠檢查上下文傳播:

不要將上下文存儲(chǔ)在結(jié)構(gòu)類型中;相反,將一個(gè) Context 明確地傳遞給每個(gè)需要它的函數(shù)。上下文應(yīng)該是第一個(gè)參數(shù),通常命名為 ctx:

func DoSomething(ctx context.Context, arg Arg) error {// ... use ctx ...}

即使函數(shù)允許,也不要傳遞nil Context。如果您不確定要使用哪個(gè)Context,請(qǐng)傳遞 context.TODO。

使用上下文值僅適用于傳輸進(jìn)程和 API 的請(qǐng)求范圍數(shù)據(jù),而不用于將可選參數(shù)傳遞給函數(shù)。

相同的上下文可以傳遞給在不同 goroutine 中運(yùn)行的函數(shù); 上下文對(duì)于多個(gè) goroutine 同時(shí)使用是安全的。

有關(guān)使用Contexts 的服務(wù)器的示例代碼,請(qǐng)參閱https://blog.golang.org/context。

索引

Variables(變量)

type CancelFunc

type Context

  • func Background() Context

  • func TODO() Context

  • func WithCancel(parent Context) (ctx Context, cancel CancelFunc)

  • func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc)

  • func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)

  • func WithValue(parent Context, key, val interface{}) Context

示例

WithCancel WithDeadline WithTimeout WithValue

包文件

context.go

變量

取消是上下文取消時(shí) Context.Err 返回的錯(cuò)誤。

var Canceled = errors.New("context canceled")

DeadlineExceeded 是 Context.Err 在上下文截止時(shí)間過后返回的錯(cuò)誤。

var DeadlineExceeded error = deadlineExceededError{}

type CancelFunc

CancelFunc通知操作放棄其工作。CancelFunc不會(huì)等待工作停止。在第一次調(diào)用之后,對(duì)CancelFunc的后續(xù)調(diào)用不起作用。

type CancelFunc func()

type Context

上下文包含截止日期,取消信號(hào)以及跨越 API 邊界的其他值。

上下文的方法可能會(huì)被多個(gè) goroutine 同時(shí)調(diào)用。

type Context interface {        // 截止日期返回代表此情境完成工作的時(shí)間        // 應(yīng)該取消。 如果沒有截止日期,截止日期返回 ok == false        // 組,對(duì)Deadline的連續(xù)調(diào)用返回相同的結(jié)果。        Deadline() (deadline time.Time, ok bool)        // 完成后,完成返回一個(gè)關(guān)閉的頻道        // 上下文應(yīng)該取消。 如果可以的話,完成可能返回 nil(零)        // 永遠(yuǎn)不會(huì)被取消。 連續(xù)調(diào)用完成返回相同的值。        //        // WithCancel 安排在完成取消時(shí)關(guān)閉完成;        // WithDeadline 安排完成時(shí)間截止        // 到期; WithTimeout 安排在完成超時(shí)時(shí)關(guān)閉        // 經(jīng)過。        //        // Done 提供在select語句中使用:        //        //  // Stream 使用 DoSomething 生成值并將它們發(fā)送出去        //  // 直到 DoSomething 返回一個(gè)錯(cuò)誤或者 ctx.Done 關(guān)閉。        //  func Stream(ctx context.Context, out chan<- Value) error {        //  	for {        //  		v, err := DoSomething(ctx)        //  		if err != nil {        //  			return err        //  		}        //  		select {        //  		case <-ctx.Done():        //  			return ctx.Err()        //  		case out <- v:        //  		}        //  	}        //  }        //        // 有關(guān)如何使用的更多示例,請(qǐng)參閱https://blog.golang.org/pipelines        // 一個(gè)Done 通道取消。        Done() <-chan struct{}        // 如果Done 尚未關(guān)閉,則Err返回nil。        // 如果完成關(guān)閉,則 Err 會(huì)返回一個(gè)非零錯(cuò)誤,以解釋原因:        // 如果上下文被取消,則取消        // 或者如果上下文的截止時(shí)間已過,則截止時(shí)間超過。        // 在Err 返回非零錯(cuò)誤之后,對(duì)Err 的連續(xù)調(diào)用返回相同的錯(cuò)誤。        Err() error        // 值返回與此上下文關(guān)聯(lián)的值相關(guān)的值,或者 nil        // 如果沒有值與鍵關(guān)聯(lián)。 Successive 調(diào)用Value        // 相同的密鑰返回相同的結(jié)果。        //        // 僅將上下文值用于傳輸?shù)恼?qǐng)求范圍數(shù)據(jù)        // 進(jìn)程和API邊界,而不是將可選參數(shù)傳遞給        // 函數(shù)。        //        // 一個(gè)關(guān)鍵字標(biāo)識(shí) Context 中的特定值。 希望的Function        // 在Context中存儲(chǔ)值通常在全局中分配一個(gè)鍵        // 然后使用該鍵作為 context.WithValue 和的參數(shù)        // Context.Value, 一個(gè)密鑰可以是支持平等的任何類型;        // 包應(yīng)該將鍵定義為未導(dǎo)出的類型以避免        // 碰撞        //        // 定義Context鍵的軟件包應(yīng)提供類型安全的訪問器        // 對(duì)于使用該鍵存儲(chǔ)的值:        //        
        // 	pac包用戶定義了存儲(chǔ)在Contexts輸入中的用戶類型。        //        // 	import "context"        //        // 	// 包用戶定義了存儲(chǔ)在上下文中的用戶類型。包用戶定義了存儲(chǔ)在上下文中的用戶類型。        // 	type User struct {...}        //        // 	// key(鍵)是此軟件包中定義的鍵的未導(dǎo)出類型。        // 	// 這可以防止與其他軟件包中定義的鍵的沖突。        // 	鍵入關(guān)鍵字int        //        // 	// userKey是用戶的關(guān)鍵。上下文中的用戶值。 它是        // 	// 未導(dǎo)出; 客戶端使用user.NewContext和user.FromContext        // 	// 而不是直接使用此密鑰。        // 	var userKey key = 0        //        // 	// NewContext 返回一個(gè)帶有值u的新Context。        // 	func NewContext(ctx context.Context, u *User) context.Context {        // 		return context.WithValue(ctx, userKey, u)        // 	}        //        // 	// FromContext返回存儲(chǔ)在ctx中的User值(如果有)。        // 	func FromContext(ctx context.Context) (*User, bool) {        // 		u, ok := ctx.Value(userKey).(*User)        // 		返回 u, ok        // 	}        Value(key interface{}) interface{}}

func Background

func Background() Context

背景返回non-nil(非零),空的 Context。它從未被取消,沒有值,也沒有最后期限。它通常由主函數(shù),初始化和測(cè)試使用,并作為傳入請(qǐng)求的top-level Context (頂級(jí)上下文)。

func TODO

func TODO() Context

TODO 返回非零空的上下文。代碼應(yīng)該使用context.TODO,當(dāng)它不清楚使用哪個(gè) Context或它尚不可用時(shí)(因?yàn)橹車暮瘮?shù)尚未擴(kuò)展為接受Context參數(shù))。TODO 被靜態(tài)分析工具識(shí)別,以確定上下文是否在程序中正確傳播。

func WithCancel

func WithCancel(parent Context) (ctx Context, cancel CancelFunc)

WithCancel 返回一個(gè)新的完成通道的父級(jí)的副本。返回的上下文的 Done 通道在返回的取消函數(shù)被調(diào)用時(shí)或父上下文的 Done 通道關(guān)閉時(shí)關(guān)閉,無論哪個(gè)先發(fā)生。

取消這個(gè)上下文會(huì)釋放與它相關(guān)的資源,所以只要完成在這個(gè)Context 中運(yùn)行的操作,代碼就應(yīng)該調(diào)用 cancel。

示例

此示例演示使用可取消上下文來防止 goroutine 泄漏。在示例函數(shù)結(jié)束時(shí),由 gen 開始的 goroutine 將返回而不會(huì)泄漏。

package mainimport ("context""fmt")func main() {// gen在單獨(dú)的goroutine中生成整數(shù)// 將它們發(fā)送到返回的頻道。// gen的調(diào)用者需要取消一次該上下文// 他們完成消耗生成的整數(shù)不泄漏// 內(nèi)部goroutine由gen開始。
	gen := func(ctx context.Context) <-chan int {
		dst := make(chan int)
		n := 1
		go func() {for {
				select {case <-ctx.Done():return // 返回不要泄漏goroutinecase dst <- n:
					n++}}}()return dst}

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel() // 當(dāng)我們完成消耗整數(shù)時(shí)取消for n := range gen(ctx) {
		fmt.Println(n)if n == 5 {break}}}

func WithDeadline

func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc)

WithDeadline 返回父上下文的副本,并將截止日期調(diào)整為不晚于d。如果父母的截止日期早于d,WithDeadline(parent,d)在語義上等同于父母。當(dāng)截止日期到期,返回的取消功能被調(diào)用時(shí),或者父上下文的完成通道關(guān)閉時(shí),返回的上下文的完成通道將關(guān)閉,以先發(fā)生者為準(zhǔn)。

取消這個(gè)上下文會(huì)釋放與它相關(guān)的資源,所以只要完成在這個(gè)Context 中運(yùn)行的操作,代碼就應(yīng)該調(diào)用cancel。

示例

這個(gè)例子傳遞一個(gè)任意期限的上下文來告訴阻塞函數(shù),它應(yīng)該盡快放棄它的工作。

package mainimport ("context""fmt""time")func main() {
	d := time.Now().Add(50 * time.Millisecond)
	ctx, cancel := context.WithDeadline(context.Background(), d)// 即使ctx過期,最好還是調(diào)用// 取消功能無論如何。 如果不這樣做可能會(huì)保留// 上下文及其父級(jí)的活動(dòng)時(shí)間超過必要時(shí)間
	defer cancel()

	select {case <-time.After(1 * time.Second):
		fmt.Println("overslept")case <-ctx.Done():
		fmt.Println(ctx.Err())}}

func WithTimeout

func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)

WithTimeout 返回 WithDeadline(parent, time.Now().Add(timeout)) 。

取消這個(gè)上下文可以釋放與它相關(guān)的資源,因此只要在這個(gè)Context 中運(yùn)行的操作完成,代碼就應(yīng)該立即調(diào)用 cancel:

func slowOperationWithTimeout(ctx context.Context) (Result, error) {
	ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
	defer cancel()  // 如果slowOperation在超時(shí)之前完成,則釋放資源return slowOperation(ctx)}

示例

這個(gè)例子傳遞一個(gè)帶有超時(shí)的上下文來告訴阻塞函數(shù),它應(yīng)該在超時(shí)過后放棄它的工作。

package mainimport ("context""fmt""time")func main() {// 傳遞帶超時(shí)的上下文告訴阻塞函數(shù)// 超時(shí)過后應(yīng)該放棄它的工作。
	ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
	defer cancel()

	select {case <-time.After(1 * time.Second):
		fmt.Println("overslept")case <-ctx.Done():
		fmt.Println(ctx.Err()) // 打印"context deadline exceeded"}}

func WithValue

func WithValue(parent Context, key, val interface{}) Context

WithValue 返回父鍵的副本,其中與鍵關(guān)聯(lián)的值是val。

使用上下文值僅適用于傳輸進(jìn)程和 API 的請(qǐng)求范圍數(shù)據(jù),而不用于將可選參數(shù)傳遞給函數(shù)。

提供的密鑰必須具有可比性,不應(yīng)該是字符串類型或任何其他內(nèi)置類型,以避免使用上下文的包之間發(fā)生沖突。WithValue 的用戶應(yīng)該為鍵定義他們自己的類型。為了避免在分配給接口時(shí)分配{},上下文鍵通常具有具體類型 struct {}?;蛘撸瑢?dǎo)出的上下文關(guān)鍵字變量的靜態(tài)類型應(yīng)該是指針或接口。

示例

package mainimport ("context""fmt")func main() {
	type favContextKey string

	f := func(ctx context.Context, k favContextKey) {if v := ctx.Value(k); v != nil {
			fmt.Println("found value:", v)return}
		fmt.Println("key not found:", k)}

	k := favContextKey("language")
	ctx := context.WithValue(context.Background(), k, "Go")f(ctx, k)f(ctx, favContextKey("color"))}
前の記事: 次の記事: