You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

604 lines
22 KiB

8 years ago
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1">
  6. <meta name="theme-color" content="#375EAB">
  7. <title>context - The Go Programming Language</title>
  8. <link type="text/css" rel="stylesheet" href="../../../../../lib/godoc/style.css">
  9. <link rel="stylesheet" href="../../../../../lib/godoc/jquery.treeview.css">
  10. <script type="text/javascript">window.initFuncs = [];</script>
  11. </head>
  12. <body>
  13. <div id='lowframe' style="position: fixed; bottom: 0; left: 0; height: 0; width: 100%; border-top: thin solid grey; background-color: white; overflow: auto;">
  14. ...
  15. </div><!-- #lowframe -->
  16. <div id="topbar" class="wide"><div class="container">
  17. <div class="top-heading" id="heading-wide"><a href="http://localhost:6060/">The Go Programming Language</a></div>
  18. <div class="top-heading" id="heading-narrow"><a href="http://localhost:6060/">Go</a></div>
  19. <a href="index.html#" id="menu-button"><span id="menu-button-arrow">&#9661;</span></a>
  20. <form method="GET" action="http://localhost:6060/search">
  21. <div id="menu">
  22. <a href="http://localhost:6060/doc/">Documents</a>
  23. <a href="http://localhost:6060/pkg/">Packages</a>
  24. <a href="http://localhost:6060/project/">The Project</a>
  25. <a href="http://localhost:6060/help/">Help</a>
  26. <a href="http://localhost:6060/blog/">Blog</a>
  27. <input type="text" id="search" name="q" class="inactive" value="Search" placeholder="Search">
  28. </div>
  29. </form>
  30. </div></div>
  31. <div id="page" class="wide">
  32. <div class="container">
  33. <h1>Package context</h1>
  34. <div id="nav"></div>
  35. <!--
  36. Copyright 2009 The Go Authors. All rights reserved.
  37. Use of this source code is governed by a BSD-style
  38. license that can be found in the LICENSE file.
  39. -->
  40. <!--
  41. Note: Static (i.e., not template-generated) href and id
  42. attributes start with "pkg-" to make it impossible for
  43. them to conflict with generated attributes (some of which
  44. correspond to Go identifiers).
  45. -->
  46. <script type='text/javascript'>
  47. document.ANALYSIS_DATA = null;
  48. document.CALLGRAPH = null;
  49. </script>
  50. <div id="short-nav">
  51. <dl>
  52. <dd><code>import "golang.org/x/net/context"</code></dd>
  53. </dl>
  54. <dl>
  55. <dd><a href="index.html#pkg-overview" class="overviewLink">Overview</a></dd>
  56. <dd><a href="index.html#pkg-index" class="indexLink">Index</a></dd>
  57. <dd><a href="index.html#pkg-examples" class="examplesLink">Examples</a></dd>
  58. <dd><a href="index.html#pkg-subdirectories">Subdirectories</a></dd>
  59. </dl>
  60. </div>
  61. <!-- The package's Name is printed as title by the top-level template -->
  62. <div id="pkg-overview" class="toggleVisible">
  63. <div class="collapsed">
  64. <h2 class="toggleButton" title="Click to show Overview section">Overview ▹</h2>
  65. </div>
  66. <div class="expanded">
  67. <h2 class="toggleButton" title="Click to hide Overview section">Overview ▾</h2>
  68. <p>
  69. Package context defines the Context type, which carries deadlines,
  70. cancelation signals, and other request-scoped values across API boundaries
  71. and between processes.
  72. </p>
  73. <p>
  74. Incoming requests to a server should create a Context, and outgoing calls to
  75. servers should accept a Context. The chain of function calls between must
  76. propagate the Context, optionally replacing it with a modified copy created
  77. using WithDeadline, WithTimeout, WithCancel, or WithValue.
  78. </p>
  79. <p>
  80. Programs that use Contexts should follow these rules to keep interfaces
  81. consistent across packages and enable static analysis tools to check context
  82. propagation:
  83. </p>
  84. <p>
  85. Do not store Contexts inside a struct type; instead, pass a Context
  86. explicitly to each function that needs it. The Context should be the first
  87. parameter, typically named ctx:
  88. </p>
  89. <pre>func DoSomething(ctx context.Context, arg Arg) error {
  90. // ... use ctx ...
  91. }
  92. </pre>
  93. <p>
  94. Do not pass a nil Context, even if a function permits it. Pass context.TODO
  95. if you are unsure about which Context to use.
  96. </p>
  97. <p>
  98. Use context Values only for request-scoped data that transits processes and
  99. APIs, not for passing optional parameters to functions.
  100. </p>
  101. <p>
  102. The same Context may be passed to functions running in different goroutines;
  103. Contexts are safe for simultaneous use by multiple goroutines.
  104. </p>
  105. <p>
  106. See <a href="http://blog.golang.org/context">http://blog.golang.org/context</a> for example code for a server that uses
  107. Contexts.
  108. </p>
  109. </div>
  110. </div>
  111. <div id="pkg-index" class="toggleVisible">
  112. <div class="collapsed">
  113. <h2 class="toggleButton" title="Click to show Index section">Index ▹</h2>
  114. </div>
  115. <div class="expanded">
  116. <h2 class="toggleButton" title="Click to hide Index section">Index ▾</h2>
  117. <!-- Table of contents for API; must be named manual-nav to turn off auto nav. -->
  118. <div id="manual-nav">
  119. <dl>
  120. <dd><a href="index.html#pkg-variables">Variables</a></dd>
  121. <dd><a href="index.html#CancelFunc">type CancelFunc</a></dd>
  122. <dd><a href="index.html#Context">type Context</a></dd>
  123. <dd>&nbsp; &nbsp; <a href="index.html#Background">func Background() Context</a></dd>
  124. <dd>&nbsp; &nbsp; <a href="index.html#TODO">func TODO() Context</a></dd>
  125. <dd>&nbsp; &nbsp; <a href="index.html#WithCancel">func WithCancel(parent Context) (ctx Context, cancel CancelFunc)</a></dd>
  126. <dd>&nbsp; &nbsp; <a href="index.html#WithDeadline">func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc)</a></dd>
  127. <dd>&nbsp; &nbsp; <a href="index.html#WithTimeout">func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)</a></dd>
  128. <dd>&nbsp; &nbsp; <a href="index.html#WithValue">func WithValue(parent Context, key interface{}, val interface{}) Context</a></dd>
  129. </dl>
  130. </div><!-- #manual-nav -->
  131. <div id="pkg-examples">
  132. <h4>Examples</h4>
  133. <dl>
  134. <dd><a class="exampleLink" href="index.html#example_WithTimeout">WithTimeout</a></dd>
  135. </dl>
  136. </div>
  137. <h4>Package files</h4>
  138. <p>
  139. <span style="font-size:90%">
  140. <a href="http://localhost:6060/src/golang.org/x/net/context/context.go">context.go</a>
  141. <a href="http://localhost:6060/src/golang.org/x/net/context/pre_go17.go">pre_go17.go</a>
  142. </span>
  143. </p>
  144. </div><!-- .expanded -->
  145. </div><!-- #pkg-index -->
  146. <div id="pkg-callgraph" class="toggle" style="display: none">
  147. <div class="collapsed">
  148. <h2 class="toggleButton" title="Click to show Internal Call Graph section">Internal call graph ▹</h2>
  149. </div> <!-- .expanded -->
  150. <div class="expanded">
  151. <h2 class="toggleButton" title="Click to hide Internal Call Graph section">Internal call graph ▾</h2>
  152. <p>
  153. In the call graph viewer below, each node
  154. is a function belonging to this package
  155. and its children are the functions it
  156. calls&mdash;perhaps dynamically.
  157. </p>
  158. <p>
  159. The root nodes are the entry points of the
  160. package: functions that may be called from
  161. outside the package.
  162. There may be non-exported or anonymous
  163. functions among them if they are called
  164. dynamically from another package.
  165. </p>
  166. <p>
  167. Click a node to visit that function's source code.
  168. From there you can visit its callers by
  169. clicking its declaring <code>func</code>
  170. token.
  171. </p>
  172. <p>
  173. Functions may be omitted if they were
  174. determined to be unreachable in the
  175. particular programs or tests that were
  176. analyzed.
  177. </p>
  178. <!-- Zero means show all package entry points. -->
  179. <ul style="margin-left: 0.5in" id="callgraph-0" class="treeview"></ul>
  180. </div>
  181. </div> <!-- #pkg-callgraph -->
  182. <h2 id="pkg-variables">Variables</h2>
  183. <pre>var <span id="Canceled">Canceled</span> = <a href="../../../../errors/index.html">errors</a>.<a href="../../../../errors/index.html#New">New</a>(&#34;context canceled&#34;)</pre>
  184. <p>
  185. Canceled is the error returned by Context.Err when the context is canceled.
  186. </p>
  187. <pre>var <span id="DeadlineExceeded">DeadlineExceeded</span> = <a href="../../../../errors/index.html">errors</a>.<a href="../../../../errors/index.html#New">New</a>(&#34;context deadline exceeded&#34;)</pre>
  188. <p>
  189. DeadlineExceeded is the error returned by Context.Err when the context&#39;s
  190. deadline passes.
  191. </p>
  192. <h2 id="CancelFunc">type <a href="http://localhost:6060/src/golang.org/x/net/context/context.go?s=6183:6205#L146">CancelFunc</a></h2>
  193. <pre>type CancelFunc func()</pre>
  194. <p>
  195. A CancelFunc tells an operation to abandon its work.
  196. A CancelFunc does not wait for the work to stop.
  197. After the first call, subsequent calls to a CancelFunc do nothing.
  198. </p>
  199. <h2 id="Context">type <a href="http://localhost:6060/src/golang.org/x/net/context/context.go?s=1850:5319#L35">Context</a></h2>
  200. <pre>type Context interface {
  201. <span class="comment">// Deadline returns the time when work done on behalf of this context</span>
  202. <span class="comment">// should be canceled. Deadline returns ok==false when no deadline is</span>
  203. <span class="comment">// set. Successive calls to Deadline return the same results.</span>
  204. Deadline() (deadline <a href="../../../../time/index.html">time</a>.<a href="../../../../time/index.html#Time">Time</a>, ok <a href="../../../../builtin/index.html#bool">bool</a>)
  205. <span class="comment">// Done returns a channel that&#39;s closed when work done on behalf of this</span>
  206. <span class="comment">// context should be canceled. Done may return nil if this context can</span>
  207. <span class="comment">// never be canceled. Successive calls to Done return the same value.</span>
  208. <span class="comment">//</span>
  209. <span class="comment">// WithCancel arranges for Done to be closed when cancel is called;</span>
  210. <span class="comment">// WithDeadline arranges for Done to be closed when the deadline</span>
  211. <span class="comment">// expires; WithTimeout arranges for Done to be closed when the timeout</span>
  212. <span class="comment">// elapses.</span>
  213. <span class="comment">//</span>
  214. <span class="comment">// Done is provided for use in select statements:</span>
  215. <span class="comment">//</span>
  216. <span class="comment">// // Stream generates values with DoSomething and sends them to out</span>
  217. <span class="comment">// // until DoSomething returns an error or ctx.Done is closed.</span>
  218. <span class="comment">// func Stream(ctx context.Context, out chan&lt;- Value) error {</span>
  219. <span class="comment">// for {</span>
  220. <span class="comment">// v, err := DoSomething(ctx)</span>
  221. <span class="comment">// if err != nil {</span>
  222. <span class="comment">// return err</span>
  223. <span class="comment">// }</span>
  224. <span class="comment">// select {</span>
  225. <span class="comment">// case &lt;-ctx.Done():</span>
  226. <span class="comment">// return ctx.Err()</span>
  227. <span class="comment">// case out &lt;- v:</span>
  228. <span class="comment">// }</span>
  229. <span class="comment">// }</span>
  230. <span class="comment">// }</span>
  231. <span class="comment">//</span>
  232. <span class="comment">// See http://blog.golang.org/pipelines for more examples of how to use</span>
  233. <span class="comment">// a Done channel for cancelation.</span>
  234. Done() &lt;-chan struct{}
  235. <span class="comment">// Err returns a non-nil error value after Done is closed. Err returns</span>
  236. <span class="comment">// Canceled if the context was canceled or DeadlineExceeded if the</span>
  237. <span class="comment">// context&#39;s deadline passed. No other values for Err are defined.</span>
  238. <span class="comment">// After Done is closed, successive calls to Err return the same value.</span>
  239. Err() <a href="../../../../builtin/index.html#error">error</a>
  240. <span class="comment">// Value returns the value associated with this context for key, or nil</span>
  241. <span class="comment">// if no value is associated with key. Successive calls to Value with</span>
  242. <span class="comment">// the same key returns the same result.</span>
  243. <span class="comment">//</span>
  244. <span class="comment">// Use context values only for request-scoped data that transits</span>
  245. <span class="comment">// processes and API boundaries, not for passing optional parameters to</span>
  246. <span class="comment">// functions.</span>
  247. <span class="comment">//</span>
  248. <span class="comment">// A key identifies a specific value in a Context. Functions that wish</span>
  249. <span class="comment">// to store values in Context typically allocate a key in a global</span>
  250. <span class="comment">// variable then use that key as the argument to context.WithValue and</span>
  251. <span class="comment">// Context.Value. A key can be any type that supports equality;</span>
  252. <span class="comment">// packages should define keys as an unexported type to avoid</span>
  253. <span class="comment">// collisions.</span>
  254. <span class="comment">//</span>
  255. <span class="comment">// Packages that define a Context key should provide type-safe accessors</span>
  256. <span class="comment">// for the values stores using that key:</span>
  257. <span class="comment">//</span>
  258. <span class="comment">// // Package user defines a User type that&#39;s stored in Contexts.</span>
  259. <span class="comment">// package user</span>
  260. <span class="comment">//</span>
  261. <span class="comment">// import &#34;golang.org/x/net/context&#34;</span>
  262. <span class="comment">//</span>
  263. <span class="comment">// // User is the type of value stored in the Contexts.</span>
  264. <span class="comment">// type User struct {...}</span>
  265. <span class="comment">//</span>
  266. <span class="comment">// // key is an unexported type for keys defined in this package.</span>
  267. <span class="comment">// // This prevents collisions with keys defined in other packages.</span>
  268. <span class="comment">// type key int</span>
  269. <span class="comment">//</span>
  270. <span class="comment">// // userKey is the key for user.User values in Contexts. It is</span>
  271. <span class="comment">// // unexported; clients use user.NewContext and user.FromContext</span>
  272. <span class="comment">// // instead of using this key directly.</span>
  273. <span class="comment">// var userKey key = 0</span>
  274. <span class="comment">//</span>
  275. <span class="comment">// // NewContext returns a new Context that carries value u.</span>
  276. <span class="comment">// func NewContext(ctx context.Context, u *User) context.Context {</span>
  277. <span class="comment">// return context.WithValue(ctx, userKey, u)</span>
  278. <span class="comment">// }</span>
  279. <span class="comment">//</span>
  280. <span class="comment">// // FromContext returns the User value stored in ctx, if any.</span>
  281. <span class="comment">// func FromContext(ctx context.Context) (*User, bool) {</span>
  282. <span class="comment">// u, ok := ctx.Value(userKey).(*User)</span>
  283. <span class="comment">// return u, ok</span>
  284. <span class="comment">// }</span>
  285. Value(key interface{}) interface{}
  286. }</pre>
  287. <p>
  288. A Context carries a deadline, a cancelation signal, and other values across
  289. API boundaries.
  290. </p>
  291. <p>
  292. Context&#39;s methods may be called by multiple goroutines simultaneously.
  293. </p>
  294. <h3 id="Background">func <a href="http://localhost:6060/src/golang.org/x/net/context/context.go?s=5559:5584#L130">Background</a></h3>
  295. <pre>func Background() <a href="index.html#Context">Context</a></pre>
  296. <p>
  297. Background returns a non-nil, empty Context. It is never canceled, has no
  298. values, and has no deadline. It is typically used by the main function,
  299. initialization, and tests, and as the top-level Context for incoming
  300. requests.
  301. </p>
  302. <h3 id="TODO">func <a href="http://localhost:6060/src/golang.org/x/net/context/context.go?s=5967:5986#L139">TODO</a></h3>
  303. <pre>func TODO() <a href="index.html#Context">Context</a></pre>
  304. <p>
  305. TODO returns a non-nil, empty Context. Code should use context.TODO when
  306. it&#39;s unclear which Context to use or it is not yet available (because the
  307. surrounding function has not yet been extended to accept a Context
  308. parameter). TODO is recognized by static analysis tools that determine
  309. whether Contexts are propagated correctly in a program.
  310. </p>
  311. <h3 id="WithCancel">func <a href="http://localhost:6060/src/golang.org/x/net/context/pre_go17.go?s=1568:1632#L54">WithCancel</a></h3>
  312. <pre>func WithCancel(parent <a href="index.html#Context">Context</a>) (ctx <a href="index.html#Context">Context</a>, cancel <a href="index.html#CancelFunc">CancelFunc</a>)</pre>
  313. <p>
  314. WithCancel returns a copy of parent with a new Done channel. The returned
  315. context&#39;s Done channel is closed when the returned cancel function is called
  316. or when the parent context&#39;s Done channel is closed, whichever happens first.
  317. </p>
  318. <p>
  319. Canceling this context releases resources associated with it, so code should
  320. call cancel as soon as the operations running in this Context complete.
  321. </p>
  322. <h3 id="WithDeadline">func <a href="http://localhost:6060/src/golang.org/x/net/context/pre_go17.go?s=5207:5282#L194">WithDeadline</a></h3>
  323. <pre>func WithDeadline(parent <a href="index.html#Context">Context</a>, deadline <a href="../../../../time/index.html">time</a>.<a href="../../../../time/index.html#Time">Time</a>) (<a href="index.html#Context">Context</a>, <a href="index.html#CancelFunc">CancelFunc</a>)</pre>
  324. <p>
  325. WithDeadline returns a copy of the parent context with the deadline adjusted
  326. to be no later than d. If the parent&#39;s deadline is already earlier than d,
  327. WithDeadline(parent, d) is semantically equivalent to parent. The returned
  328. context&#39;s Done channel is closed when the deadline expires, when the returned
  329. cancel function is called, or when the parent context&#39;s Done channel is
  330. closed, whichever happens first.
  331. </p>
  332. <p>
  333. Canceling this context releases resources associated with it, so code should
  334. call cancel as soon as the operations running in this Context complete.
  335. </p>
  336. <h3 id="WithTimeout">func <a href="http://localhost:6060/src/golang.org/x/net/context/pre_go17.go?s=7228:7305#L261">WithTimeout</a></h3>
  337. <pre>func WithTimeout(parent <a href="index.html#Context">Context</a>, timeout <a href="../../../../time/index.html">time</a>.<a href="../../../../time/index.html#Duration">Duration</a>) (<a href="index.html#Context">Context</a>, <a href="index.html#CancelFunc">CancelFunc</a>)</pre>
  338. <p>
  339. WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)).
  340. </p>
  341. <p>
  342. Canceling this context releases resources associated with it, so code should
  343. call cancel as soon as the operations running in this Context complete:
  344. </p>
  345. <pre>func slowOperationWithTimeout(ctx context.Context) (Result, error) {
  346. ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
  347. defer cancel() // releases resources if slowOperation completes before timeout elapses
  348. return slowOperation(ctx)
  349. }
  350. </pre>
  351. <div id="example_WithTimeout" class="toggle">
  352. <div class="collapsed">
  353. <p class="exampleHeading toggleButton"><span class="text">Example</span></p>
  354. </div>
  355. <div class="expanded">
  356. <p class="exampleHeading toggleButton"><span class="text">Example</span></p>
  357. <p>Code:</p>
  358. <pre class="code"><span class="comment">// Pass a context with a timeout to tell a blocking function that it</span>
  359. <span class="comment">// should abandon its work after the timeout elapses.</span>
  360. ctx, _ := context.WithTimeout(context.Background(), 100*time.Millisecond)
  361. select {
  362. case &lt;-time.After(200 * time.Millisecond):
  363. fmt.Println(&#34;overslept&#34;)
  364. case &lt;-ctx.Done():
  365. fmt.Println(ctx.Err()) <span class="comment">// prints &#34;context deadline exceeded&#34;</span>
  366. }
  367. <span class="comment"></pre>
  368. <p>Output:</p>
  369. <pre class="output">context deadline exceeded
  370. </pre>
  371. </div>
  372. </div>
  373. <h3 id="WithValue">func <a href="http://localhost:6060/src/golang.org/x/net/context/pre_go17.go?s=7594:7666#L270">WithValue</a></h3>
  374. <pre>func WithValue(parent <a href="index.html#Context">Context</a>, key interface{}, val interface{}) <a href="index.html#Context">Context</a></pre>
  375. <p>
  376. WithValue returns a copy of parent in which the value associated with key is
  377. val.
  378. </p>
  379. <p>
  380. Use context Values only for request-scoped data that transits processes and
  381. APIs, not for passing optional parameters to functions.
  382. </p>
  383. <h2 id="pkg-subdirectories">Subdirectories</h2>
  384. <div class="pkg-dir">
  385. <table>
  386. <tr>
  387. <th class="pkg-name">Name</th>
  388. <th class="pkg-synopsis">Synopsis</th>
  389. </tr>
  390. <tr>
  391. <td colspan="2"><a href="../index.html">..</a></td>
  392. </tr>
  393. <tr>
  394. <td class="pkg-name" style="padding-left: 0px;">
  395. <a href="ctxhttp/index.html">ctxhttp</a>
  396. </td>
  397. <td class="pkg-synopsis">
  398. Package ctxhttp provides helper functions for performing context-aware HTTP requests.
  399. </td>
  400. </tr>
  401. </table>
  402. </div>
  403. <div id="footer">
  404. Build version go1.6.<br>
  405. Except as <a href="https://developers.google.com/site-policies#restrictions">noted</a>,
  406. the content of this page is licensed under the
  407. Creative Commons Attribution 3.0 License,
  408. and code is licensed under a <a href="http://localhost:6060/LICENSE">BSD license</a>.<br>
  409. <a href="http://localhost:6060/doc/tos.html">Terms of Service</a> |
  410. <a href="http://www.google.com/intl/en/policies/privacy/">Privacy Policy</a>
  411. </div>
  412. </div><!-- .container -->
  413. </div><!-- #page -->
  414. <!-- TODO(adonovan): load these from <head> using "defer" attribute? -->
  415. <script type="text/javascript" src="../../../../../lib/godoc/jquery.js"></script>
  416. <script type="text/javascript" src="../../../../../lib/godoc/jquery.treeview.js"></script>
  417. <script type="text/javascript" src="../../../../../lib/godoc/jquery.treeview.edit.js"></script>
  418. <script type="text/javascript" src="../../../../../lib/godoc/godocs.js"></script>
  419. </body>
  420. </html>