本文整理汇总了Golang中golang.org/x/net/context.Context.Err方法的典型用法代码示例。如果您正苦于以下问题:Golang Context.Err方法的具体用法?Golang Context.Err怎么用?Golang Context.Err使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类golang.org/x/net/context.Context
的用法示例。
在下文中一共展示了Context.Err方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Upload
// Upload is called to perform the upload.
func (u *mockUploadDescriptor) Upload(ctx context.Context, progressOutput progress.Output) (distribution.Descriptor, error) {
if u.currentUploads != nil {
defer atomic.AddInt32(u.currentUploads, -1)
if atomic.AddInt32(u.currentUploads, 1) > maxUploadConcurrency {
return distribution.Descriptor{}, errors.New("concurrency limit exceeded")
}
}
// Sleep a bit to simulate a time-consuming upload.
for i := int64(0); i <= 10; i++ {
select {
case <-ctx.Done():
return distribution.Descriptor{}, ctx.Err()
case <-time.After(10 * time.Millisecond):
progressOutput.WriteProgress(progress.Progress{ID: u.ID(), Current: i, Total: 10})
}
}
if u.simulateRetries != 0 {
u.simulateRetries--
return distribution.Descriptor{}, errors.New("simulating retry")
}
return distribution.Descriptor{}, nil
}
示例2: processInternalRaftRequest
func (s *EtcdServer) processInternalRaftRequest(ctx context.Context, r pb.InternalRaftRequest) (*applyResult, error) {
r.ID = s.reqIDGen.Next()
data, err := r.Marshal()
if err != nil {
return nil, err
}
if len(data) > maxRequestBytes {
return nil, ErrRequestTooLarge
}
ch := s.w.Register(r.ID)
s.r.Propose(ctx, data)
select {
case x := <-ch:
return x.(*applyResult), nil
case <-ctx.Done():
s.w.Trigger(r.ID, nil) // GC wait
return nil, ctx.Err()
case <-s.done:
return nil, ErrStopped
}
}
示例3: runExec
func runExec(ctx context.Context, db *sql.DB, query string) error {
done := make(chan struct{})
var (
errMsg error
)
go func() {
for {
if _, err := db.Exec(query); err != nil {
errMsg = err
time.Sleep(time.Second)
continue
} else {
errMsg = nil
done <- struct{}{}
break
}
}
}()
select {
case <-done:
return errMsg
case <-ctx.Done():
return fmt.Errorf("runExec %s timed out with %v / %v", query, ctx.Err(), errMsg)
}
}
示例4: waitForStateChange
// waitForStateChange blocks until the state changes to something other than the sourceState.
func (ac *addrConn) waitForStateChange(ctx context.Context, sourceState ConnectivityState) (ConnectivityState, error) {
ac.mu.Lock()
defer ac.mu.Unlock()
if sourceState != ac.state {
return ac.state, nil
}
done := make(chan struct{})
var err error
go func() {
select {
case <-ctx.Done():
ac.mu.Lock()
err = ctx.Err()
ac.stateCV.Broadcast()
ac.mu.Unlock()
case <-done:
}
}()
defer close(done)
for sourceState == ac.state {
ac.stateCV.Wait()
if err != nil {
return ac.state, err
}
}
return ac.state, nil
}
示例5: WaitSelect
// WaitSelect waits until at least one remote becomes available and then selects one.
func (s *persistentRemotes) WaitSelect(ctx context.Context) <-chan api.Peer {
c := make(chan api.Peer, 1)
s.RLock()
done := make(chan struct{})
go func() {
select {
case <-ctx.Done():
s.c.Broadcast()
case <-done:
}
}()
go func() {
defer s.RUnlock()
defer close(c)
defer close(done)
for {
if ctx.Err() != nil {
return
}
p, err := s.Select()
if err == nil {
c <- p
return
}
s.c.Wait()
}
}()
return c
}
示例6: wait
// wait blocks until i) the new transport is up or ii) ctx is done or iii) ac is closed.
func (ac *addrConn) wait(ctx context.Context) (transport.ClientTransport, error) {
for {
ac.mu.Lock()
switch {
case ac.state == Shutdown:
ac.mu.Unlock()
return nil, errConnClosing
case ac.state == Ready:
ct := ac.transport
ac.mu.Unlock()
return ct, nil
default:
ready := ac.ready
if ready == nil {
ready = make(chan struct{})
ac.ready = ready
}
ac.mu.Unlock()
select {
case <-ctx.Done():
return nil, transport.ContextErr(ctx.Err())
// Wait until the new transport is ready or failed.
case <-ready:
}
}
}
}
示例7: configure
// configure sends a configuration change through consensus and
// then waits for it to be applied to the server. It will block
// until the change is performed or there is an error.
func (n *Node) configure(ctx context.Context, cc raftpb.ConfChange) error {
cc.ID = n.reqIDGen.Next()
ctx, cancel := context.WithCancel(ctx)
ch := n.wait.register(cc.ID, nil, cancel)
if err := n.raftNode.ProposeConfChange(ctx, cc); err != nil {
n.wait.cancel(cc.ID)
return err
}
select {
case x := <-ch:
if err, ok := x.(error); ok {
return err
}
if x != nil {
log.G(ctx).Panic("raft: configuration change error, return type should always be error")
}
return nil
case <-ctx.Done():
n.wait.cancel(cc.ID)
return ctx.Err()
}
}
示例8: Wait
// Wait blocks until i) the new transport is up or ii) ctx is done or iii)
func (cc *Conn) Wait(ctx context.Context) (transport.ClientTransport, error) {
for {
cc.mu.Lock()
switch {
case cc.state == Shutdown:
cc.mu.Unlock()
return nil, ErrClientConnClosing
case cc.state == Ready:
cc.mu.Unlock()
return cc.transport, nil
case cc.state == TransientFailure:
cc.mu.Unlock()
// Break out so that the caller gets chance to pick another transport to
// perform rpc instead of sticking to this transport.
return nil, ErrTransientFailure
default:
ready := cc.ready
if ready == nil {
ready = make(chan struct{})
cc.ready = ready
}
cc.mu.Unlock()
select {
case <-ctx.Done():
return nil, transport.ContextErr(ctx.Err())
// Wait until the new transport is ready or failed.
case <-ready:
}
}
}
}
示例9: RunScript
func (i *localInstance) RunScript(ctx gocontext.Context, writer io.Writer) (*RunResult, error) {
if i.scriptPath == "" {
return &RunResult{Completed: false}, errNoScriptUploaded
}
cmd := exec.Command("bash", i.scriptPath)
cmd.Stdout = writer
cmd.Stderr = writer
err := cmd.Start()
if err != nil {
return &RunResult{Completed: false}, err
}
errChan := make(chan error)
go func() {
errChan <- cmd.Wait()
}()
select {
case err := <-errChan:
if err != nil {
return &RunResult{Completed: false}, err
}
return &RunResult{Completed: true}, nil
case <-ctx.Done():
err = ctx.Err()
if err != nil {
return &RunResult{Completed: false}, err
}
return &RunResult{Completed: true}, nil
}
}
示例10: EnumerateBlobs
func (m *mongoStorage) EnumerateBlobs(ctx context.Context, dest chan<- blob.SizedRef, after string, limit int) error {
defer close(dest)
var b blobDoc
var qry bson.M
if after != "" {
qry = bson.M{"key": bson.M{"$gt": after}}
}
iter := m.c.Find(qry).Limit(limit).Select(bson.M{"key": 1, "size": 1}).Sort("key").Iter()
for iter.Next(&b) {
br, ok := blob.Parse(b.Key)
if !ok {
continue
}
select {
case dest <- blob.SizedRef{Ref: br, Size: uint32(b.Size)}:
case <-ctx.Done():
// Close the iterator but ignore the error value since we are already cancelling
if err := iter.Close(); err != nil {
log.Printf("Error closing iterator after enumerating: %v", err)
}
return ctx.Err()
}
}
if err := iter.Close(); err != nil {
return err
}
return nil
}
示例11: Retry
// Retry invokes the given function, retrying it multiple times if the connection failed or
// the HTTP status response indicates the request should be attempted again. ctx may be nil.
func Retry(ctx context.Context, f func() (*http.Response, error), backoff BackoffStrategy) (*http.Response, error) {
for {
resp, err := f()
var status int
if resp != nil {
status = resp.StatusCode
}
// Return if we shouldn't retry.
pause, retry := backoff.Pause()
if !shouldRetry(status, err) || !retry {
return resp, err
}
// Ensure the response body is closed, if any.
if resp != nil && resp.Body != nil {
resp.Body.Close()
}
// Pause, but still listen to ctx.Done if context is not nil.
var done <-chan struct{}
if ctx != nil {
done = ctx.Done()
}
select {
case <-done:
return nil, ctx.Err()
case <-time.After(pause):
}
}
}
示例12: Do
// Do sends an HTTP request with the provided http.Client and returns an HTTP response.
// If the client is nil, http.DefaultClient is used.
// If the context is canceled or times out, ctx.Err() will be returned.
func Do(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) {
if client == nil {
client = http.DefaultClient
}
// Request cancelation changed in Go 1.5, see cancelreq.go and cancelreq_go14.go.
cancel := canceler(client, req)
type responseAndError struct {
resp *http.Response
err error
}
result := make(chan responseAndError, 1)
// Make local copies of test hooks closed over by goroutines below.
// Prevents data races in tests.
testHookDoReturned := testHookDoReturned
testHookDidBodyClose := testHookDidBodyClose
go func() {
resp, err := client.Do(req)
testHookDoReturned()
result <- responseAndError{resp, err}
}()
var resp *http.Response
select {
case <-ctx.Done():
testHookContextDoneBeforeHeaders()
cancel()
// Clean up after the goroutine calling client.Do:
go func() {
if r := <-result; r.resp != nil {
testHookDidBodyClose()
r.resp.Body.Close()
}
}()
return nil, ctx.Err()
case r := <-result:
var err error
resp, err = r.resp, r.err
if err != nil {
return resp, err
}
}
c := make(chan struct{})
go func() {
select {
case <-ctx.Done():
cancel()
case <-c:
// The response's Body is closed.
}
}()
resp.Body = ¬ifyingReader{resp.Body, c}
return resp, nil
}
示例13: Handle
func (h *testHandler) Handle(ctx context.Context, args *raw.Args) (*raw.Res, error) {
h.Lock()
h.format = args.Format
h.caller = args.Caller
h.Unlock()
assert.Equal(h.t, args.Caller, CurrentCall(ctx).CallerName())
switch args.Method {
case "block":
<-ctx.Done()
h.blockErr <- ctx.Err()
return &raw.Res{
IsErr: true,
}, nil
case "echo":
return &raw.Res{
Arg2: args.Arg2,
Arg3: args.Arg3,
}, nil
case "busy":
return &raw.Res{
SystemErr: ErrServerBusy,
}, nil
case "app-error":
return &raw.Res{
IsErr: true,
}, nil
}
return nil, errors.New("unknown method")
}
示例14: Wait
// Wait blocks until i) the new transport is up or ii) ctx is done or iii) cc is closed.
func (cc *Conn) Wait(ctx context.Context) (transport.ClientTransport, error) {
// 等待? 为什么等待呢?
for {
cc.mu.Lock()
switch {
// 1. 如果Conn关闭,则直接报错
case cc.state == Shutdown:
cc.mu.Unlock()
return nil, ErrClientConnClosing
// 2. 如果Ready, 则返回: Transport
case cc.state == Ready:
ct := cc.transport
cc.mu.Unlock()
return ct, nil
default:
// 3. 其他情况下,等待Ready or Done
ready := cc.ready
if ready == nil {
ready = make(chan struct{})
cc.ready = ready
}
cc.mu.Unlock()
select {
case <-ctx.Done():
return nil, transport.ContextErr(ctx.Err())
// Wait until the new transport is ready or failed.
case <-ready:
}
}
}
}
示例15: WaitN
// WaitN blocks until lim permits n events to happen.
// It returns an error if n exceeds the Limiter's burst size, the Context is
// canceled, or the expected wait time exceeds the Context's Deadline.
func (lim *Limiter) WaitN(ctx context.Context, n int) (err error) {
if n > lim.burst {
return fmt.Errorf("rate: Wait(n=%d) exceeds limiter's burst %d", n, lim.burst)
}
// Check if ctx is already cancelled
select {
case <-ctx.Done():
return ctx.Err()
default:
}
// Determine wait limit
now := time.Now()
waitLimit := InfDuration
if deadline, ok := ctx.Deadline(); ok {
waitLimit = deadline.Sub(now)
}
// Reserve
r := lim.reserveN(now, n, waitLimit)
if !r.ok {
return fmt.Errorf("rate: Wait(n=%d) would exceed context deadline", n)
}
// Wait
t := time.NewTimer(r.DelayFrom(now))
defer t.Stop()
select {
case <-t.C:
// We can proceed.
return nil
case <-ctx.Done():
// Context was canceled before we could proceed. Cancel the
// reservation, which may permit other events to proceed sooner.
r.Cancel()
return ctx.Err()
}
}