{"id":3544,"date":"2021-07-03T10:41:34","date_gmt":"2021-07-03T02:41:34","guid":{"rendered":"https:\/\/wyxxt.org.cn\/?p=3544"},"modified":"2023-12-04T15:18:51","modified_gmt":"2023-12-04T07:18:51","slug":"go%e8%af%ad%e8%a8%80context","status":"publish","type":"post","link":"https:\/\/wyxxt.org.cn\/?p=3544","title":{"rendered":"go\u8bed\u8a00context"},"content":{"rendered":"<h2>\u4ecb\u7ecd<\/h2>\n<p>Go Concurrency Patterns: Context<\/p>\n<p>\u5728 Go \u670d\u52a1\u5668\u4e2d\uff0c\u6bcf\u4e2a\u4f20\u5165\u8bf7\u6c42\u90fd\u5728\u5176\u81ea\u5df1\u7684 goroutine \u4e2d\u5904\u7406\u3002\u8bf7\u6c42\u5904\u7406\u7a0b\u5e8f\u901a\u5e38\u4f1a\u542f\u52a8\u989d\u5916\u7684 goroutine \u6765\u8bbf\u95ee\u540e\u7aef\uff0c\u4f8b\u5982\u6570\u636e\u5e93\u548c RPC \u670d\u52a1\u3002\u5904\u7406\u8bf7\u6c42\u7684\u4e00\u7ec4 goroutine \u901a\u5e38\u9700\u8981\u8bbf\u95ee\u7279\u5b9a\u4e8e\u8bf7\u6c42\u7684\u503c\uff0c\u4f8b\u5982\u6700\u7ec8\u7528\u6237\u7684\u8eab\u4efd\u3001\u6388\u6743\u4ee4\u724c\u548c\u8bf7\u6c42\u7684\u622a\u6b62\u65e5\u671f\u3002\u5f53\u8bf7\u6c42\u88ab\u53d6\u6d88\u6216\u8d85\u65f6\u65f6\uff0c\u5904\u7406\u8be5\u8bf7\u6c42\u7684\u6240\u6709 goroutine \u90fd\u5e94\u8be5\u5feb\u901f\u9000\u51fa\uff0c\u4ee5\u4fbf\u7cfb\u7edf\u53ef\u4ee5\u56de\u6536\u5b83\u4eec\u6b63\u5728\u4f7f\u7528\u7684\u4efb\u4f55\u8d44\u6e90\u3002<\/p>\n<p>Google\u5f00\u53d1\u4e86\u4e00\u4e2a<code>context<\/code>\u5305\uff0c\u53ef\u4ee5\u8f7b\u677e\u5730\u5c06\u8bf7\u6c42\u8303\u56f4\u7684\u503c\u3001\u53d6\u6d88\u4fe1\u53f7\u548c\u622a\u6b62\u65e5\u671f\u8de8 API \u8fb9\u754c\u4f20\u9012\u7ed9\u5904\u7406\u8bf7\u6c42\u6240\u6d89\u53ca\u7684\u6240\u6709 goroutine\u3002\u8be5\u5305\u4f5c\u4e3a<a class=\"wp-editor-md-post-content-link\" href=\"https:\/\/pkg.go.dev\/context\">context<\/a>\u516c\u5f00\u53ef\u7528 \u3002<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/oss.wyxxt.org.cn\/images\/2021\/09\/18\/wp_editor_md_85c33b20f5ce03584af52456f25612b0.jpg\" alt=\"\" \/><\/p>\n<h2>\u524d\u7f6e\u77e5\u8bc6<\/h2>\n<blockquote><p>\n  Done() \u65b9\u6cd5\u8fd4\u56de\u4e00\u4e2achannel<\/p>\n<p>  cancel\u3001timeout\u3001deadline \u8fd9\u4e09\u79cd\u60c5\u51b5\uff0c\u4f1aclose channel<\/p>\n<p>  \u7531\u4e8eclose channel \u6240\u6709\u534f\u7a0b\u90fd\u80fd\u76d1\u542c\u5230\uff0c\u6240\u4ee5\u6240\u6709goroutine\u90fd\u53ef\u4ee5\u5173\u95ed<\/p>\n<p>  \u7279\u522b\u6ce8\u610f\uff0c\u9664\u4e86close\u64cd\u4f5c\uff0c\u5f80channel\u4e2d\u5199\u5165\u4e00\u6761\u6570\u636e\u65f6\uff0c\u53ea\u80fd\u6709\u4e00\u4e2agoroutine\u80fd\u51b2channel\u4e2d\u83b7\u53d6\u5230\u6570\u636e\n<\/p><\/blockquote>\n<h2>\u8bed\u5883<\/h2>\n<p>context\u5305\u7684\u6838\u5fc3\u662fContext\u7c7b\u578b<\/p>\n<pre><code class=\"language-go line-numbers\">\/\/ \u4e0a\u4e0b\u6587\u643a\u5e26\u622a\u6b62\u65e5\u671f\u3001\u53d6\u6d88\u4fe1\u53f7\u548c\u8bf7\u6c42\u8303\u56f4\u7684\u503c\n\/\/ \u8de8\u8d8aAPI\u8fb9\u754c\u3002\u4ed6\u7684\u65b9\u6cd5\u5bf9\u4e8e\u591agoroutine\u540c\u65f6\u4f7f\u7528\u662f\u5b89\u5168\u7684\ntype Context interface{\n    \/\/ Done returns a channel that is closed when this Context is canceled\n    \/\/ or times out.\n    Done() &lt;-chan struct{}\n\n    \/\/ Err indicates why this context was canceled, after the Done channel\n    \/\/ is closed.\n    Err() error\n\n    \/\/ Deadline returns the time when this Context will be canceled, if any.\n    Deadline() (deadline time.Time, ok bool)\n\n    \/\/ Value returns the value associated with key or nil if none.\n    Value(key interface{}) interface{}\n}\n<\/code><\/pre>\n<h2>\u6d3e\u751f\u4e0a\u4e0b\u6587<\/h2>\n<p>\u8be5<code>context<\/code>\u5305\u63d0\u4f9b\u4e86\u4ece\u73b0\u6709\u503c\u4e2d<em>\u6d3e\u751f\u51fa<\/em>\u65b0<code>Context<\/code>\u503c\u7684\u51fd\u6570\u3002\u8fd9\u4e9b\u503c\u5f62\u6210\u4e00\u68f5\u6811\uff1a\u5f53 a<code>Context<\/code>\u88ab\u53d6\u6d88\u65f6\uff0c\u6240\u6709<code>Contexts<\/code>\u4ece\u5b83\u6d3e\u751f\u7684\u4e5f\u88ab\u53d6\u6d88\u3002<\/p>\n<p><code>Background<\/code>\u662f\u4efb\u4f55<code>Context<\/code>\u6811\u7684\u6839\uff1b\u5b83\u6c38\u8fdc\u4e0d\u4f1a\u88ab\u53d6\u6d88\uff1a<\/p>\n<pre><code class=\"language-go line-numbers\">\/\/ Background returns an empty Context. It is never canceled, has no deadline,\n\/\/ and has no values. Background is typically used in main, init, and tests,\n\/\/ and as the top-level Context for incoming requests.\nfunc Background() Context\n<\/code><\/pre>\n<p><code>WithCancel<\/code>\u548c<code>WithTimeout<\/code>\u8fd4\u56de\u884d\u751f<code>Context<\/code>\u503c\uff0c\u53ef\u4ee5\u6bd4\u7236<code>Context<\/code>\u66f4\u5feb\u5730\u53d6\u6d88\u3002\u5f53\u8bf7\u6c42\u5904\u7406\u7a0b\u5e8f\u8fd4\u56de\u65f6\uff0c\u901a\u5e38\u4f1a\u53d6\u6d88\u4e0e\u4f20\u5165\u8bf7\u6c42\u76f8\u5173\u7684<code>Context<\/code>\u3002<code>WithCancel<\/code>\u8fd8\u53ef\u7528\u4e8e\u5728\u4f7f\u7528\u591a\u4e2a\u526f\u672c\u65f6\u53d6\u6d88\u5197\u4f59\u8bf7\u6c42\u3002<code>WithTimeout<\/code>\u53ef\u7528\u4e8e\u4e3a\u540e\u7aef\u670d\u52a1\u5668\u8bf7\u6c42\u8bbe\u7f6e\u622a\u6b62\u65e5\u671f<\/p>\n<pre><code class=\"language-go line-numbers\">\/\/ WithCancel returns a copy of parent whose Done channel is closed as soon as\n\/\/ parent.Done is closed or cancel is called.\nfunc WithCancel(parent Context) (ctx Context, cancel CancelFunc)\n\n\/\/ A CancelFunc cancels a Context.\ntype CancelFunc func()\n\n\/\/ WithTimeout returns a copy of parent whose Done channel is closed as soon as\n\/\/ parent.Done is closed, cancel is called, or timeout elapses. The new\n\/\/ Context's Deadline is the sooner of now+timeout and the parent's deadline, if\n\/\/ any. If the timer is still running, the cancel function releases its\n\/\/ resources.\nfunc WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)\n\n\/\/ WithDeadline returns a copy of the parent context with the deadline adjusted\n\/\/ to be no later than d. If the parent's deadline is already earlier than d,\n\/\/ WithDeadline(parent, d) is semantically equivalent to parent. The returned\n\/\/ context's Done channel is closed when the deadline expires, when the returned\n\/\/ cancel function is called, or when the parent context's Done channel is\n\/\/ closed, whichever happens first.\n\/\/\n\/\/ Canceling this context releases resources associated with it, so code should\n\/\/ call cancel as soon as the operations running in this Context complete.\nfunc WithDeadline(parent Context, d time.Time) (Context, CancelFunc)\n<\/code><\/pre>\n<p><code>WithValue<\/code>\u63d0\u4f9b\u4e86\u4e00\u79cd\u65b9\u6cd5\uff0c\u5c06\u8bf7\u6c42\u8303\u56f4\u7684\u503c\u4e0e<code>Context<\/code>\u5173\u8054<\/p>\n<pre><code class=\"language-go line-numbers\">\/\/ WithValue returns a copy of parent whose Value method returns val for key.\nfunc WithValue(parent Context, key interface{}, val interface{}) Context\n<\/code><\/pre>\n<h2>\u793a\u4f8b<\/h2>\n<pre><code class=\"language-go line-numbers\">\/**\n * Createby GoLand\n * User xzw jsjxzw@163.com\n * Date 2021\/7\/3\n * Time \u4e0b\u53481:46\n *\/\n\npackage main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"net\/http\"\n    \"time\"\n)\n\nfunc main() {\n    http.HandleFunc(\"\/\", SayHello)\n\n    log.Fatalln(http.ListenAndServe(\":8080\", nil))\n}\n\nfunc SayHello(writer http.ResponseWriter, request *http.Request) {\n    fmt.Println(&amp;request)\n\n    go func() {\n        for range time.Tick(time.Second) {\n            select {\n            case &lt;-request.Context().Done():\n                fmt.Println(\"request is outgoing\")\n                return\n            default:\n                fmt.Println(\"Current request is in progress\")\n            }\n        }\n    }()\n\n    time.Sleep(2 * time.Second)\n\n    writer.Write([]byte(\"Hi\"))\n}\n\n<\/code><\/pre>\n<p><img decoding=\"async\" src=\"https:\/\/oss.wyxxt.org.cn\/images\/2021\/09\/18\/wp_editor_md_79bf13116e92ac7c672905581aff21ec.jpg\" alt=\"\" \/><\/p>\n<h2>\u4f5c\u7528<\/h2>\n<p>\u5728 Go \u8bed\u8a00\u4e2d context \u5305\u5141\u8bb8\u60a8\u4f20\u9012\u4e00\u4e2a &#8220;context&#8221; \u5230\u60a8\u7684\u7a0b\u5e8f\u3002 Context \u5982\u8d85\u65f6\u6216\u622a\u6b62\u65e5\u671f\uff08deadline\uff09\u6216\u901a\u9053\uff0c\u6765\u6307\u793a\u505c\u6b62\u8fd0\u884c\u548c\u8fd4\u56de\u3002\u4f8b\u5982\uff0c\u5982\u679c\u60a8\u6b63\u5728\u6267\u884c\u4e00\u4e2a web \u8bf7\u6c42\u6216\u8fd0\u884c\u4e00\u4e2a\u7cfb\u7edf\u547d\u4ee4\uff0c\u5b9a\u4e49\u4e00\u4e2a\u8d85\u65f6\u5bf9\u751f\u4ea7\u7ea7\u7cfb\u7edf\u901a\u5e38\u662f\u4e2a\u597d\u4e3b\u610f\u3002\u56e0\u4e3a\uff0c\u5982\u679c\u60a8\u4f9d\u8d56\u7684API\u8fd0\u884c\u7f13\u6162\uff0c\u4f60\u4e0d\u5e0c\u671b\u5728\u7cfb\u7edf\u4e0a\u5907\u4efd\uff08back up\uff09\u8bf7\u6c42\uff0c\u56e0\u4e3a\u5b83\u53ef\u80fd\u6700\u7ec8\u4f1a\u589e\u52a0\u8d1f\u8f7d\u5e76\u964d\u4f4e\u6240\u6709\u8bf7\u6c42\u7684\u6267\u884c\u6548\u7387\u3002\u5bfc\u81f4\u7ea7\u8054\u6548\u5e94\u3002\u8fd9\u662f\u8d85\u65f6\u6216\u622a\u6b62\u65e5\u671f context \u6d3e\u4e0a\u7528\u573a\u7684\u5730\u65b9\u3002<\/p>\n<h2>\u8bbe\u8ba1\u539f\u7406<\/h2>\n<p>Go \u8bed\u8a00\u4e2d\u7684\u6bcf\u4e00\u4e2a\u8bf7\u6c42\u7684\u90fd\u662f\u901a\u8fc7\u4e00\u4e2a\u5355\u72ec\u7684 Goroutine \u8fdb\u884c\u5904\u7406\u7684\uff0cHTTP\/RPC \u8bf7\u6c42\u7684\u5904\u7406\u5668\u5f80\u5f80\u90fd\u4f1a\u542f\u52a8\u65b0\u7684 Goroutine \u8bbf\u95ee\u6570\u636e\u5e93\u548c RPC \u670d\u52a1\uff0c\u6211\u4eec\u53ef\u80fd\u4f1a\u521b\u5efa\u591a\u4e2a Goroutine \u6765\u5904\u7406\u4e00\u6b21\u8bf7\u6c42\uff0c\u800c <code>Context<\/code> \u7684\u4e3b\u8981\u4f5c\u7528\u5c31\u662f\u5728\u4e0d\u540c\u7684 Goroutine \u4e4b\u95f4\u540c\u6b65\u8bf7\u6c42\u7279\u5b9a\u7684\u6570\u636e\u3001\u53d6\u6d88\u4fe1\u53f7\u4ee5\u53ca\u5904\u7406\u8bf7\u6c42\u7684\u622a\u6b62\u65e5\u671f\u3002<\/p>\n<p><a class=\"wp-editor-md-post-content-link\" href=\"https:\/\/www.processon.com\/view\/link\/60f134701efad41bbea74c9c\">context\u5305\u8bbe\u8ba1\u539f\u7406<\/a><\/p>\n<pre><code class=\"language-go line-numbers\">\/**\n * Createby GoLand\n * User xzw jsjxzw@163.com\n * Date 2021\/7\/3\n * Time \u4e0b\u53482:14\n *\/\n\npackage main\n\nimport (\n    \"context\"\n    \"fmt\"\n    \"time\"\n)\n\nfunc main() {\n    ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)\n    defer cancel()\n    go helloHandle(ctx, 2*time.Second)\n    select {\n    case &lt;-ctx.Done(): \/\/\u6b64\u5904\u963b\u585e2s\n        fmt.Println(\"Hello Handle\", ctx.Err())\n    }\n    time.Sleep(3 * time.Second)\n}\n\nfunc helloHandle(ctx context.Context, duration time.Duration) {\n    select {\n    case &lt;-ctx.Done():\n        fmt.Println(ctx.Err())\n    case &lt;-time.Tick(duration):\n        fmt.Println(\"process request with\", duration)\n    }\n}\n\n<\/code><\/pre>\n<p><img decoding=\"async\" src=\"https:\/\/oss.wyxxt.org.cn\/images\/2021\/09\/18\/wp_editor_md_c948d1e0fda5ac7fe5d396037f06ec01.jpg\" alt=\"\" \/><\/p>\n<h2>\u4f7f\u7528\u573a\u666f<\/h2>\n<h3>RPC\u8c03\u7528<\/h3>\n<p>\u5728\u4e3bgoroutine\u4e0a\u67094\u4e2aRPC\uff0cRPC2\/3\/4\u662f\u5e76\u884c\u8bf7\u6c42\u7684\uff0c\u6211\u4eec\u8fd9\u91cc\u5e0c\u671b\u5728RPC2\u8bf7\u6c42\u5931\u8d25\u4e4b\u540e\uff0c\u76f4\u63a5\u8fd4\u56de\u9519\u8bef\uff0c\u5e76\u4e14\u8ba9RPC3\/4\u505c\u6b62\u7ee7\u7eed\u8ba1\u7b97\u3002\u8fd9\u4e2a\u65f6\u5019\uff0c\u5c31\u4f7f\u7528\u7684\u5230Context\u3002<\/p>\n<pre><code class=\"language-go line-numbers\">package main\n\nimport (\n    \"context\"\n    \"sync\"\n    \"github.com\/pkg\/errors\"\n)\n\nfunc Rpc(ctx context.Context, url string) error {\n    result := make(chan int)\n    err := make(chan error)\n\n    go func() {\n        \/\/ \u8fdb\u884cRPC\u8c03\u7528\uff0c\u5e76\u4e14\u8fd4\u56de\u662f\u5426\u6210\u529f\uff0c\u6210\u529f\u901a\u8fc7result\u4f20\u9012\u6210\u529f\u4fe1\u606f\uff0c\u9519\u8bef\u901a\u8fc7error\u4f20\u9012\u9519\u8bef\u4fe1\u606f\n        isSuccess := true\n        if isSuccess {\n            result &lt;- 1\n        } else {\n            err &lt;- errors.New(\"some error happen\")\n        }\n    }()\n\n    select {\n        case &lt;- ctx.Done():\n            \/\/ \u5176\u4ed6RPC\u8c03\u7528\u8c03\u7528\u5931\u8d25\n            return ctx.Err()\n        case e := &lt;- err:\n            \/\/ \u672cRPC\u8c03\u7528\u5931\u8d25\uff0c\u8fd4\u56de\u9519\u8bef\u4fe1\u606f\n            return e\n        case &lt;- result:\n            \/\/ \u672cRPC\u8c03\u7528\u6210\u529f\uff0c\u4e0d\u8fd4\u56de\u9519\u8bef\u4fe1\u606f\n            return nil\n    }\n}\n\n\nfunc main() {\n    ctx, cancel := context.WithCancel(context.Background())\n\n    \/\/ RPC1\u8c03\u7528\n    err := Rpc(ctx, \"http:\/\/rpc_1_url\")\n    if err != nil {\n        return\n    }\n\n    wg := sync.WaitGroup{}\n\n    \/\/ RPC2\u8c03\u7528\n    wg.Add(1)\n    go func(){\n        defer wg.Done()\n        err := Rpc(ctx, \"http:\/\/rpc_2_url\")\n        if err != nil {\n            cancel()\n        }\n    }()\n\n    \/\/ RPC3\u8c03\u7528\n    wg.Add(1)\n    go func(){\n        defer wg.Done()\n        err := Rpc(ctx, \"http:\/\/rpc_3_url\")\n        if err != nil {\n            cancel()\n        }\n    }()\n\n    \/\/ RPC4\u8c03\u7528\n    wg.Add(1)\n    go func(){\n        defer wg.Done()\n        err := Rpc(ctx, \"http:\/\/rpc_4_url\")\n        if err != nil {\n            cancel()\n        }\n    }()\n\n    wg.Wait()\n}\n<\/code><\/pre>\n<h3>PipeLine<\/h3>\n<p>pipeline\u6a21\u5f0f\u5c31\u662f\u6d41\u6c34\u7ebf\u6a21\u578b\uff0c\u6d41\u6c34\u7ebf\u4e0a\u7684\u51e0\u4e2a\u5de5\u4eba\uff0c\u6709n\u4e2a\u4ea7\u54c1\uff0c\u4e00\u4e2a\u4e00\u4e2a\u4ea7\u54c1\u8fdb\u884c\u7ec4\u88c5\u3002\u5176\u5b9epipeline\u6a21\u578b\u7684\u5b9e\u73b0\u548cContext\u5e76\u65e0\u5173\u7cfb\uff0c\u6ca1\u6709context\u6211\u4eec\u4e5f\u80fd\u7528chan\u5b9e\u73b0pipeline\u6a21\u578b\u3002\u4f46\u662f\u5bf9\u4e8e\u6574\u6761\u6d41\u6c34\u7ebf\u7684\u63a7\u5236\uff0c\u5219\u662f\u9700\u8981\u4f7f\u7528\u4e0aContext\u7684\u3002<\/p>\n<h3>\u8d85\u65f6\u8bf7\u6c42<\/h3>\n<p>\u6211\u4eec\u53d1\u9001RPC\u8bf7\u6c42\u7684\u65f6\u5019\uff0c\u5f80\u5f80\u5e0c\u671b\u5bf9\u8fd9\u4e2a\u8bf7\u6c42\u8fdb\u884c\u4e00\u4e2a\u8d85\u65f6\u7684\u9650\u5236\u3002\u5f53\u4e00\u4e2aRPC\u8bf7\u6c42\u8d85\u8fc710s\u7684\u8bf7\u6c42\uff0c\u81ea\u52a8\u65ad\u5f00\u3002\u5f53\u7136\u6211\u4eec\u4f7f\u7528CancelContext\uff0c\u4e5f\u80fd\u5b9e\u73b0\u8fd9\u4e2a\u529f\u80fd\uff08\u5f00\u542f\u4e00\u4e2a\u65b0\u7684goroutine\uff0c\u8fd9\u4e2agoroutine\u62ff\u7740cancel\u51fd\u6570\uff0c\u5f53\u65f6\u95f4\u5230\u4e86\uff0c\u5c31\u8c03\u7528cancel\u51fd\u6570\uff09\u3002<\/p>\n<p>\u9274\u4e8e\u8fd9\u4e2a\u9700\u6c42\u662f\u975e\u5e38\u5e38\u89c1\u7684\uff0ccontext\u5305\u4e5f\u5b9e\u73b0\u4e86\u8fd9\u4e2a\u9700\u6c42\uff1atimerCtx\u3002\u5177\u4f53\u5b9e\u4f8b\u5316\u7684\u65b9\u6cd5\u662f WithDeadline \u548c WithTimeout\u3002<\/p>\n<p>\u5177\u4f53\u7684timerCtx\u91cc\u9762\u7684\u903b\u8f91\u4e5f\u5c31\u662f\u901a\u8fc7time.AfterFunc\u6765\u8c03\u7528ctx.cancel\u7684\u3002<\/p>\n<pre><code class=\"language-go line-numbers\">package main\n\nimport (\n    \"context\"\n    \"fmt\"\n    \"time\"\n)\n\nfunc main() {\n    ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)\n    defer cancel()\n\n    select {\n    case &lt;-time.After(1 * time.Second):\n        fmt.Println(\"overslept\")\n    case &lt;-ctx.Done():\n        fmt.Println(ctx.Err()) \/\/ prints \"context deadline exceeded\"\n    }\n}\n<\/code><\/pre>\n<p>http\u7684\u5ba2\u6237\u7aef\u91cc\u9762\u52a0\u4e0atimeout\u4e5f\u662f\u4e00\u4e2a\u5e38\u89c1\u7684\u529e\u6cd5<\/p>\n<pre><code class=\"language-go line-numbers\">uri := \"https:\/\/httpbin.org\/delay\/3\"\nreq, err := http.NewRequest(\"GET\", uri, nil)\nif err != nil {\n    log.Fatalf(\"http.NewRequest() failed with '%s'\\n\", err)\n}\n\nctx, _ := context.WithTimeout(context.Background(), time.Millisecond*100)\nreq = req.WithContext(ctx)\n\nresp, err := http.DefaultClient.Do(req)\nif err != nil {\n    log.Fatalf(\"http.DefaultClient.Do() failed with:\\n'%s'\\n\", err)\n}\ndefer resp.Body.Close()\n<\/code><\/pre>\n<h3>HTTP\u670d\u52a1\u5668\u7684request\u4e92\u76f8\u4f20\u9012\u6570\u636e<\/h3>\n<p>context\u8fd8\u63d0\u4f9b\u4e86valueCtx\u7684\u6570\u636e\u7ed3\u6784\u3002<\/p>\n<p>\u8fd9\u4e2avalueCtx\u6700\u7ecf\u5e38\u4f7f\u7528\u7684\u573a\u666f\u5c31\u662f\u5728\u4e00\u4e2ahttp\u670d\u52a1\u5668\u4e2d\uff0c\u5728request\u4e2d\u4f20\u9012\u4e00\u4e2a\u7279\u5b9a\u503c\uff0c\u6bd4\u5982\u6709\u4e00\u4e2a\u4e2d\u95f4\u4ef6\uff0c\u505acookie\u9a8c\u8bc1\uff0c\u7136\u540e\u628a\u9a8c\u8bc1\u540e\u7684\u7528\u6237\u540d\u5b58\u653e\u5728request\u4e2d\u3002<\/p>\n<p>\u6211\u4eec\u53ef\u4ee5\u770b\u5230\uff0c\u5b98\u65b9\u7684request\u91cc\u9762\u662f\u5305\u542b\u4e86Context\u7684\uff0c\u5e76\u4e14\u63d0\u4f9b\u4e86WithContext\u7684\u65b9\u6cd5\u8fdb\u884ccontext\u7684\u66ff\u6362\u3002<\/p>\n<pre><code class=\"language-go line-numbers\">package main\n\nimport (\n    \"net\/http\"\n    \"context\"\n)\n\ntype FooKey string\n\nvar UserName = FooKey(\"user-name\")\nvar UserId = FooKey(\"user-id\")\n\nfunc foo(next http.HandlerFunc) http.HandlerFunc {\n    return func(w http.ResponseWriter, r *http.Request) {\n        ctx := context.WithValue(r.Context(), UserId, \"1\")\n        ctx2 := context.WithValue(ctx, UserName, \"yejianfeng\")\n        next(w, r.WithContext(ctx2))\n    }\n}\n\nfunc GetUserName(context context.Context) string {\n    if ret, ok := context.Value(UserName).(string); ok {\n        return ret\n    }\n    return \"\"\n}\n\nfunc GetUserId(context context.Context) string {\n    if ret, ok := context.Value(UserId).(string); ok {\n        return ret\n    }\n    return \"\"\n}\n\nfunc test(w http.ResponseWriter, r *http.Request) {\n    w.Write([]byte(\"welcome: \"))\n    w.Write([]byte(GetUserId(r.Context())))\n    w.Write([]byte(\" \"))\n    w.Write([]byte(GetUserName(r.Context())))\n}\n\nfunc main() {\n    http.Handle(\"\/\", foo(test))\n    http.ListenAndServe(\":8080\", nil)\n}\n<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>\u4ecb\u7ecd Go Concurrency Patterns: Context \u5728 Go \u670d\u52a1\u5668\u4e2d\uff0c\u6bcf\u4e2a\u4f20\u5165\u8bf7\u6c42\u90fd\u5728\u5176 [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[15],"tags":[398],"class_list":["post-3544","post","type-post","status-publish","format-standard","hentry","category-15","tag-go"],"_links":{"self":[{"href":"https:\/\/wyxxt.org.cn\/index.php?rest_route=\/wp\/v2\/posts\/3544","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/wyxxt.org.cn\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/wyxxt.org.cn\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/wyxxt.org.cn\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/wyxxt.org.cn\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=3544"}],"version-history":[{"count":5,"href":"https:\/\/wyxxt.org.cn\/index.php?rest_route=\/wp\/v2\/posts\/3544\/revisions"}],"predecessor-version":[{"id":3636,"href":"https:\/\/wyxxt.org.cn\/index.php?rest_route=\/wp\/v2\/posts\/3544\/revisions\/3636"}],"wp:attachment":[{"href":"https:\/\/wyxxt.org.cn\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=3544"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/wyxxt.org.cn\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=3544"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/wyxxt.org.cn\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=3544"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}