{"id":208269,"date":"2025-07-08T08:37:04","date_gmt":"2025-07-08T00:37:04","guid":{"rendered":"https:\/\/server.hk\/cnblog\/208269\/"},"modified":"2025-07-08T08:37:04","modified_gmt":"2025-07-08T00:37:04","slug":"%e5%9c%a8-go-%e4%b8%ad%e4%bd%bf%e7%94%a8-context-withtimeout-%e6%97%b6%e7%9a%84%e6%9c%80%e4%bd%b3%e5%ae%9e%e8%b7%b5%e6%98%af%e4%bb%80%e4%b9%88%ef%bc%9f","status":"publish","type":"post","link":"https:\/\/server.hk\/cnblog\/208269\/","title":{"rendered":"\u5728 Go \u4e2d\u4f7f\u7528 context.WithTimeout() \u65f6\u7684\u6700\u4f73\u5b9e\u8df5\u662f\u4ec0\u4e48\uff1f"},"content":{"rendered":"<p><b><\/b> <\/p>\n<p>\u5f53\u524d\u4f4d\u7f6e\uff1a <span>&gt;<\/span> <span>&gt;<\/span> <span>&gt;<\/span> <span>&gt;<\/span> <span>\u5728 Go \u4e2d\u4f7f\u7528 context.WithTimeout() \u65f6\u7684\u6700\u4f73\u5b9e\u8df5\u662f\u4ec0\u4e48\uff1f<\/span><\/p>\n<p><span>\u6765\u6e90\uff1astackoverflow<\/span><br \/>\n<span>2024-05-01 08:15:32<\/span><br \/>\n<span><i><\/i>0\u6d4f\u89c8<\/span><br \/>\n<span style=\"cursor: pointer\"><i><\/i>\u6536\u85cf<\/span> <\/p>\n<p>Golang\u5c0f\u767d\u4e00\u679a\uff0c\u6b63\u5728\u4e0d\u65ad\u5b66\u4e60\u79ef\u7d2f\u77e5\u8bc6\uff0c\u73b0\u5c06\u5b66\u4e60\u5230\u7684\u77e5\u8bc6\u8bb0\u5f55\u4e00\u4e0b\uff0c\u4e5f\u662f\u5c06\u6211\u7684\u6240\u5f97\u5206\u4eab\u7ed9\u5927\u5bb6\uff01\u800c\u4eca\u5929\u8fd9\u7bc7\u6587\u7ae0\u300a\u5728 Go \u4e2d\u4f7f\u7528 context.WithTimeout() \u65f6\u7684\u6700\u4f73\u5b9e\u8df5\u662f\u4ec0\u4e48\uff1f\u300b\u5e26\u5927\u5bb6\u6765\u4e86\u89e3\u4e00\u4e0b##content_title##\uff0c\u5e0c\u671b\u5bf9\u5927\u5bb6\u7684\u77e5\u8bc6\u79ef\u7d2f\u6709\u6240\u5e2e\u52a9\uff0c\u4ece\u800c\u5f25\u8865\u81ea\u5df1\u7684\u4e0d\u8db3\uff0c\u52a9\u529b\u5b9e\u6218\u5f00\u53d1\uff01<\/p>\n<p><\/p>\n<p> \u95ee\u9898\u5185\u5bb9<br \/>\n <\/p>\n<p>\u6211\u60f3\u4f7f\u7528 <code>context.withtimeout()<\/code> \u6765\u5904\u7406\u6211\u53d1\u51fa\u5916\u90e8\u8bf7\u6c42\u7684\u7528\u4f8b\uff0c\u5982\u679c\u8bf7\u6c42\u7684\u54cd\u5e94\u592a\u957f\uff0c\u5219\u4f1a\u8fd4\u56de\u9519\u8bef\u3002<\/p>\n<p>\u6211\u5df2\u7ecf\u5b9e\u73b0\u4e86\u4f2a\u4ee3\u7801\uff0c\u5982\u4e0b\u9762\u9644\u52a0\u7684\u6f14\u793a\u94fe\u63a5\uff1a 2\u89e3\u51b3\u65b9\u6848\uff1a<\/p>\n<ul>\n<li>\u9884\u8ba1\u4e0d\u4f1a\u51fa\u73b0 main -&gt;<\/li>\n<li>\u9884\u8ba1\u4e3a main_1 -&gt;<\/li>\n<\/ul>\n<pre>package main\n\nimport (\n    \"context\"\n    \"fmt\"\n    \"time\"\n)\n\n\/\/ I just dummy sleep in this func to produce use case this func\n\/\/ need 10s to process and handle logic. \n\/\/ And this assume will be out of timeOut expect (5s)\nfunc makeHTTPRequest(ctx context.Context) (string, error) {\n    time.Sleep(time.Duration(10) * time.Second)\n    return \"abc\", nil\n}\n\n\/\/ In main Func, I will set timeout is 5 second. \nfunc main() {\n    var strCh = make(chan string, 1)\n    ctx, cancel := context.WithTimeout(context.Background(), time.Duration(5)*time.Second)\n    defer cancel()\n\n    fmt.Print(\"Begin make request\\n\")\n    abc, err := makeHTTPRequest(ctx)\n    if err != nil {\n        fmt.Print(\"Return error\\n\")\n        return\n    }\n\n    select {\n    case &lt;-ctx.Done():\n        fmt.Printf(\"Return ctx error: %s\\n\", ctx.Err())\n        return\n    case strCh &lt;- abc:\n        fmt.Print(\"Return response\\n\")\n        return\n    }\n}\n\nfunc main_1() {\n    var strCh = make(chan string, 1)\n    var errCh = make(chan error, 1)\n    ctx, cancel := context.WithTimeout(context.Background(), time.Duration(5)*time.Second)\n    defer cancel()\n\n    go func() {\n        fmt.Print(\"Begin make request\\n\")\n        abc, err := makeHTTPRequest(ctx)\n        if err != nil {\n            fmt.Print(\"Return error\\n\")\n            errCh &lt;- err\n            return\n        }\n        strCh &lt;- abc\n\n    }()\n    select {\n    case err := &lt;-errCh:\n        fmt.Printf(\"Return error: %s\\n\", err.Error())\n        return\n    case &lt;-ctx.Done():\n        fmt.Printf(\"Return ctx error: %s\\n\", ctx.Err())\n        return\n    case str := &lt;-strCh:\n        fmt.Printf(\"Return response: %s\\n\", str)\n        return\n    }\n}\n<\/pre>\n<p>\u4f46\u662f\uff0c\u5982\u679c\u4f7f\u7528 <code>main()<\/code> \u51fd\u6570\uff0c\u5219\u5b83\u65e0\u6cd5\u6309\u9884\u671f\u5de5\u4f5c\u3002 \u4f46\u662f\u5982\u679c\u7b2c\u4e8c\u4e2a <code>main_1()<\/code> \u4f7f\u7528 goroutine \u5b9e\u73b0\uff0c\u90a3\u4e48\u65b0\u7684 <code>context.withtimeout()<\/code> \u53ef\u80fd\u4f1a\u6309\u9884\u671f\u5de5\u4f5c\u3002<\/p>\n<p>\u4f60\u80fd\u5e2e\u6211\u89e3\u7b54\u4e00\u4e0b\u8fd9\u4e2a\u95ee\u9898\u5417\uff1f<\/p>\n<p>https:\/\/play.golang.org\/p\/kzdlm_tvljy<\/p>\n<p> <\/p>\n<h2>\u89e3\u51b3\u65b9\u6848<\/h2>\n<p> <\/p>\n<p>\u6700\u597d\u5728 <code>makehttprequest()<\/code> \u51fd\u6570\u4e2d\u5904\u7406\u4e0a\u4e0b\u6587\uff0c\u8fd9\u6837\u60a8\u5c31\u53ef\u4ee5\u5c06\u5176\u7528\u4f5c <code>main()<\/code> \u4e2d\u7684\u540c\u6b65\u51fd\u6570\u3002<\/p>\n<\/p>\n<pre>func makeHTTPRequest(ctx context.Context) (string, error) {\n    ch := make(chan string)\n\n    go func() {\n        time.Sleep(10 * time.Second)\n        select {\n        case ch &lt;- \"abc\":\n        default:\n            \/\/ When context deadline exceeded, there is no receiver\n            \/\/ This case will prevent goroutine blocking forever\n            return\n        }\n    }()\n\n    select {\n    case &lt;-ctx.Done():\n        return \"\", ctx.Err()\n    case result := &lt;-ch:\n        return result, nil\n    }\n}\n\nfunc main() {\n    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n    defer cancel()\n\n    fmt.Printf(\"[%v] Begin make request \\n\", time.Now())\n    abc, err := makeHTTPRequest(ctx)\n    if err != nil {\n        fmt.Printf(\"[%v] Return error: %v \\n\", time.Now(), err)\n        return\n    }\n    fmt.Printf(\"[%v] %s\", time.Now(), abc)\n}\n<\/pre>\n<p>\u5982\u679c\u6211\u6ca1\u731c\u9519\u7684\u8bdd\u3002\u6709\u4e24\u4e2a\u95ee\u9898\u3002<\/p>\n<ol>\n<li>\u60a8\u60f3\u77e5\u9053\u4e3a\u4ec0\u4e48 main() \u51fd\u6570\u4e0d\u8d77\u4f5c\u7528\uff1f<\/li>\n<li>\u6700\u4f73\u505a\u6cd5\u662f\u4ec0\u4e48\uff1f<\/li>\n<\/ol>\n<h3>\u7b2c\u4e00\u5b63\u5ea6<\/h3>\n<p><code>main()<\/code> \u5728 makehttprequest \u5904\u88ab\u963b\u6b62\uff0c\u5728\u6b64\u671f\u95f4\uff0c\u4e0a\u4e0b\u6587\u8d85\u65f6\u3002\u56e0\u6b64\uff0c\u6ca1\u6709\u6309\u9884\u671f\u5de5\u4f5c\u3002<\/p>\n<h3>\u7b2c\u4e8c\u5b63\u5ea6<\/h3>\n<p>\u8fd9\u4e2a\u53ef\u4ee5\u56de\u7b54\u4f60\u3002\u5728 <code>main_1()<\/code> \u4e2d\uff0c\u60a8\u7684\u4ee3\u7801\u5df2\u7ecf\u662f\u6700\u4f73\u5b9e\u8df5\u3002<\/p>\n<p>\u597d\u4e86\uff0c\u672c\u6587\u5230\u6b64\u7ed3\u675f\uff0c\u5e26\u5927\u5bb6\u4e86\u89e3\u4e86\u300a\u5728 Go \u4e2d\u4f7f\u7528 context.WithTimeout() \u65f6\u7684\u6700\u4f73\u5b9e\u8df5\u662f\u4ec0\u4e48\uff1f\u300b\uff0c\u5e0c\u671b\u672c\u6587\u5bf9\u4f60\u6709\u6240\u5e2e\u52a9\uff01\u5173\u6ce8\u516c\u4f17\u53f7\uff0c\u7ed9\u5927\u5bb6\u5206\u4eab\u66f4\u591aGolang\u77e5\u8bc6\uff01<\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u5f53\u524d\u4f4d\u7f6e\uff1a &gt; &gt; &#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[4925],"tags":[],"class_list":["post-208269","post","type-post","status-publish","format-standard","hentry","category-4925"],"_links":{"self":[{"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/posts\/208269","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/comments?post=208269"}],"version-history":[{"count":0,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/posts\/208269\/revisions"}],"wp:attachment":[{"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/media?parent=208269"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/categories?post=208269"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/tags?post=208269"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}