当前位置: 首页>>代码示例>>Golang>>正文


Golang Context.Err方法代码示例

本文整理汇总了Golang中context.Context.Err方法的典型用法代码示例。如果您正苦于以下问题:Golang Context.Err方法的具体用法?Golang Context.Err怎么用?Golang Context.Err使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在context.Context的用法示例。


在下文中一共展示了Context.Err方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: do

func (c *Client) do(ctx context.Context, req *http.Request) (*http.Response, error) {
	if nil == ctx || nil == ctx.Done() { // ctx.Done() is for ctx
		return c.Client.Do(req)
	}

	var resc = make(chan *http.Response, 1)
	var errc = make(chan error, 1)

	// Perform request from separate routine.
	go func() {
		res, err := c.Client.Do(req)
		if err != nil {
			errc <- err
		} else {
			resc <- res
		}
	}()

	// Wait for request completion of context expiry.
	select {
	case <-ctx.Done():
		c.t.CancelRequest(req)
		return nil, ctx.Err()
	case err := <-errc:
		return nil, err
	case res := <-resc:
		return res, nil
	}
}
开发者ID:frapposelli,项目名称:govmomi,代码行数:29,代码来源:client.go

示例2: paintLines

func paintLines(ctx context.Context, r io.Reader, source string) {
	scanner := bufio.NewScanner(r)
	doneC := ctx.Done()
	for scanner.Scan() {
		lsp.Println(source, scanner.Text())
		select {
		case <-doneC:
			break
		default:
			// do nothing
		}
	}

	if err := ctx.Err(); err != nil {
		errC <- err
		return
	}

	if err := scanner.Err(); err != nil {
		errC <- err
		return
	}

	errC <- nil
}
开发者ID:suapapa,项目名称:tools,代码行数:25,代码来源:hilog.go

示例3: WaitForResult

// WaitForResult wraps govmomi operations and wait the operation to complete.
// Return the operation result
// Sample usage:
//    info, err := WaitForResult(ctx, func(ctx) (*TaskInfo, error) {
//       return vm, vm.Reconfigure(ctx, config)
//    })
func WaitForResult(ctx context.Context, f func(context.Context) (Task, error)) (*types.TaskInfo, error) {
	var err error
	var info *types.TaskInfo
	var backoffFactor int64 = 1

	for {
		var t Task
		if t, err = f(ctx); err == nil {
			info, err = t.WaitForResult(ctx, nil)
			if err == nil {
				return info, err
			}
		}

		if !isTaskInProgress(err) {
			return info, err
		}

		sleepValue := time.Duration(backoffFactor * (rand.Int63n(100) + int64(50)))
		select {
		case <-time.After(sleepValue * time.Millisecond):
			backoffFactor *= 2
			if backoffFactor > maxBackoffFactor {
				backoffFactor = maxBackoffFactor
			}
		case <-ctx.Done():
			return info, ctx.Err()
		}

		log.Warnf("retrying task")
	}
}
开发者ID:vmware,项目名称:vic,代码行数:38,代码来源:waiter.go

示例4: cgoLookupPTR

func cgoLookupPTR(ctx context.Context, addr string) (names []string, err error, completed bool) {
	var zone string
	ip := parseIPv4(addr)
	if ip == nil {
		ip, zone = parseIPv6(addr, true)
	}
	if ip == nil {
		return nil, &DNSError{Err: "invalid address", Name: addr}, true
	}
	sa, salen := cgoSockaddr(ip, zone)
	if sa == nil {
		return nil, &DNSError{Err: "invalid address " + ip.String(), Name: addr}, true
	}
	if ctx.Done() == nil {
		names, err := cgoLookupAddrPTR(addr, sa, salen)
		return names, err, true
	}
	result := make(chan reverseLookupResult, 1)
	go cgoReverseLookup(result, addr, sa, salen)
	select {
	case r := <-result:
		return r.names, r.err, true
	case <-ctx.Done():
		return nil, mapErr(ctx.Err()), false
	}
}
开发者ID:deferpanic,项目名称:gorump,代码行数:26,代码来源:cgo_unix.go

示例5: dialPlan9

func dialPlan9(ctx context.Context, net string, laddr, raddr Addr) (fd *netFD, err error) {
	defer func() { fixErr(err) }()
	type res struct {
		fd  *netFD
		err error
	}
	resc := make(chan res)
	go func() {
		testHookDialChannel()
		fd, err := dialPlan9Blocking(ctx, net, laddr, raddr)
		select {
		case resc <- res{fd, err}:
		case <-ctx.Done():
			if fd != nil {
				fd.Close()
			}
		}
	}()
	select {
	case res := <-resc:
		return res.fd, res.err
	case <-ctx.Done():
		return nil, mapErr(ctx.Err())
	}
}
开发者ID:2thetop,项目名称:go,代码行数:25,代码来源:ipsock_plan9.go

示例6: ScanFilesToBytes

// ScanFiles takes a chanel of files
func ScanFilesToBytes(ctx context.Context, in chan File) chan Content {

	out := make(chan Content)

	go func() {

		defer close(out)

		for {
			select {
			case value, open := <-in:
				if !open {
					return
				}
				if value.Err != nil {
					out <- Content{"", nil, kerr.Wrap("PQUCOUYLJE", value.Err)}
					return
				}
				bytes, err := ProcessFile(value.File)
				// process returns Bytes == nil for non json files, so we should skip them
				if bytes != nil || err != nil {
					out <- Content{value.File, bytes, err}
				}
			case <-ctx.Done():
				out <- Content{"", nil, kerr.Wrap("AFBJCTFOKX", ctx.Err())}
				return
			}
		}

	}()

	return out

}
开发者ID:kego,项目名称:ke,代码行数:35,代码来源:scanner.go

示例7: ctxDriverBegin

func ctxDriverBegin(ctx context.Context, ci driver.Conn) (driver.Tx, error) {
	if ciCtx, is := ci.(driver.ConnBeginContext); is {
		return ciCtx.BeginContext(ctx)
	}

	if ctx.Done() == context.Background().Done() {
		return ci.Begin()
	}

	// Check the transaction level in ctx. If set and non-default
	// then return an error here as the BeginContext driver value is not supported.
	if level, ok := driver.IsolationFromContext(ctx); ok && level != driver.IsolationLevel(LevelDefault) {
		return nil, errors.New("sql: driver does not support non-default isolation level")
	}

	// Check for a read-only parameter in ctx. If a read-only transaction is
	// requested return an error as the BeginContext driver value is not supported.
	if ro := driver.ReadOnlyFromContext(ctx); ro {
		return nil, errors.New("sql: driver does not support read-only transactions")
	}

	txi, err := ci.Begin()
	if err == nil {
		select {
		default:
		case <-ctx.Done():
			txi.Rollback()
			return nil, ctx.Err()
		}
	}
	return txi, err
}
开发者ID:oshimaya,项目名称:go,代码行数:32,代码来源:ctxutil.go

示例8: Loop

func (s *subscriber) Loop(ctx context.Context, q Queue) error {
	var (
		opened bool = true
		m      *protocol.Message
	)
	sCtx, cancel := context.WithCancel(ctx)
	s.cancel = cancel
	defer func() { s.cancel = nil }()

	for opened {
		select {
		case m, opened = <-s.route.MessagesChannel():
			if !opened {
				break
			}

			q.Push(NewRequest(s, m))
		case <-sCtx.Done():
			// If the parent context is still running then only this subscriber context
			// has been cancelled
			if ctx.Err() == nil {
				return sCtx.Err()
			}
			return nil
		}
	}

	//TODO Cosmin Bogdan returning this error can mean 2 things: overflow of route's channel, or intentional stopping of router / gubled.
	return ErrRouteChannelClosed
}
开发者ID:smancke,项目名称:guble,代码行数:30,代码来源:subscriber.go

示例9: Update

// Update replace an item by a new one in the mongo collection
func (m *Handler) Update(ctx context.Context, item *resource.Item, original *resource.Item) error {
	mItem := newMongoItem(item)
	c, err := m.c(ctx)
	if err != nil {
		return err
	}
	defer m.close(c)
	err = c.Update(bson.M{"_id": original.ID, "_etag": original.ETag}, mItem)
	if err == mgo.ErrNotFound {
		// Determine if the item is not found or if the item is found but etag missmatch
		var count int
		count, err = c.FindId(original.ID).Count()
		if err != nil {
			// The find returned an unexpected err, just forward it with no mapping
		} else if count == 0 {
			err = resource.ErrNotFound
		} else if ctx.Err() != nil {
			err = ctx.Err()
		} else {
			// If the item were found, it means that its etag didn't match
			err = resource.ErrConflict
		}
	}
	return err
}
开发者ID:rs,项目名称:rest-layer-mongo,代码行数:26,代码来源:mongo.go

示例10: lookupProtocol

// lookupProtocol looks up IP protocol name and returns correspondent protocol number.
func lookupProtocol(ctx context.Context, name string) (int, error) {
	// GetProtoByName return value is stored in thread local storage.
	// Start new os thread before the call to prevent races.
	type result struct {
		proto int
		err   error
	}
	ch := make(chan result) // unbuffered
	go func() {
		acquireThread()
		defer releaseThread()
		runtime.LockOSThread()
		defer runtime.UnlockOSThread()
		proto, err := getprotobyname(name)
		select {
		case ch <- result{proto: proto, err: err}:
		case <-ctx.Done():
		}
	}()
	select {
	case r := <-ch:
		if r.err != nil {
			if proto, err := lookupProtocolMap(name); err == nil {
				return proto, nil
			}
			r.err = &DNSError{Err: r.err.Error(), Name: name}
		}
		return r.proto, r.err
	case <-ctx.Done():
		return 0, mapErr(ctx.Err())
	}
}
开发者ID:achanda,项目名称:go,代码行数:33,代码来源:lookup_windows.go

示例11: GetMany

func (ds *dagService) GetMany(ctx context.Context, keys []*cid.Cid) <-chan *NodeOption {
	out := make(chan *NodeOption, len(keys))
	blocks := ds.Blocks.GetBlocks(ctx, keys)
	var count int

	go func() {
		defer close(out)
		for {
			select {
			case b, ok := <-blocks:
				if !ok {
					if count != len(keys) {
						out <- &NodeOption{Err: fmt.Errorf("failed to fetch all nodes")}
					}
					return
				}

				nd, err := decodeBlock(b)
				if err != nil {
					out <- &NodeOption{Err: err}
					return
				}

				out <- &NodeOption{Node: nd}
				count++

			case <-ctx.Done():
				out <- &NodeOption{Err: ctx.Err()}
				return
			}
		}
	}()
	return out
}
开发者ID:qnib,项目名称:go-ipfs,代码行数:34,代码来源:merkledag.go

示例12: PerformRequests

func (e *apiClient) PerformRequests(ctx context.Context, queries []QueryToSend) (*tsdb.QueryResult, error) {
	queryResult := &tsdb.QueryResult{}

	queryCount := len(queries)
	jobsChan := make(chan QueryToSend, queryCount)
	resultChan := make(chan []*tsdb.TimeSeries, queryCount)
	errorsChan := make(chan error, 1)
	for w := 1; w <= MaxWorker; w++ {
		go e.spawnWorker(ctx, w, jobsChan, resultChan, errorsChan)
	}

	for _, v := range queries {
		jobsChan <- v
	}
	close(jobsChan)

	resultCounter := 0
	for {
		select {
		case timeseries := <-resultChan:
			queryResult.Series = append(queryResult.Series, timeseries...)
			resultCounter++

			if resultCounter == queryCount {
				close(resultChan)
				return queryResult, nil
			}
		case err := <-errorsChan:
			return nil, err
		case <-ctx.Done():
			return nil, ctx.Err()
		}
	}
}
开发者ID:mapr,项目名称:grafana,代码行数:34,代码来源:httpClient.go

示例13: EnumerateChildrenAsync

func EnumerateChildrenAsync(ctx context.Context, ds DAGService, c *cid.Cid, visit func(*cid.Cid) bool) error {
	toprocess := make(chan []*cid.Cid, 8)
	nodes := make(chan *NodeOption, 8)

	ctx, cancel := context.WithCancel(ctx)
	defer cancel()
	defer close(toprocess)

	go fetchNodes(ctx, ds, toprocess, nodes)

	root, err := ds.Get(ctx, c)
	if err != nil {
		return err
	}

	nodes <- &NodeOption{Node: root}
	live := 1

	for {
		select {
		case opt, ok := <-nodes:
			if !ok {
				return nil
			}

			if opt.Err != nil {
				return opt.Err
			}

			nd := opt.Node

			// a node has been fetched
			live--

			var cids []*cid.Cid
			for _, lnk := range nd.Links() {
				c := lnk.Cid
				if visit(c) {
					live++
					cids = append(cids, c)
				}
			}

			if live == 0 {
				return nil
			}

			if len(cids) > 0 {
				select {
				case toprocess <- cids:
				case <-ctx.Done():
					return ctx.Err()
				}
			}
		case <-ctx.Done():
			return ctx.Err()
		}
	}
}
开发者ID:qnib,项目名称:go-ipfs,代码行数:59,代码来源:merkledag.go

示例14: populateShard

// PopulateShard gets data for predicate pred from server with id serverId and
// writes it to RocksDB.
func populateShard(ctx context.Context, pl *pool, group uint32) (int, error) {
	gkeys, err := generateGroup(group)
	if err != nil {
		return 0, x.Wrapf(err, "While generating keys group")
	}

	conn, err := pl.Get()
	if err != nil {
		return 0, err
	}
	defer pl.Put(conn)
	c := NewWorkerClient(conn)

	stream, err := c.PredicateData(context.Background(), gkeys)
	if err != nil {
		return 0, err
	}
	x.Trace(ctx, "Streaming data for group: %v", group)

	kvs := make(chan *task.KV, 1000)
	che := make(chan error)
	go writeBatch(ctx, kvs, che)

	// We can use count to check the number of posting lists returned in tests.
	count := 0
	for {
		kv, err := stream.Recv()
		if err == io.EOF {
			break
		}
		if err != nil {
			close(kvs)
			return count, err
		}
		count++

		// We check for errors, if there are no errors we send value to channel.
		select {
		case kvs <- kv:
			// OK
		case <-ctx.Done():
			x.TraceError(ctx, x.Errorf("Context timed out while streaming group: %v", group))
			close(kvs)
			return count, ctx.Err()
		case err := <-che:
			x.TraceError(ctx, x.Errorf("Error while doing a batch write for group: %v", group))
			close(kvs)
			return count, err
		}
	}
	close(kvs)

	if err := <-che; err != nil {
		x.TraceError(ctx, x.Errorf("Error while doing a batch write for group: %v", group))
		return count, err
	}
	x.Trace(ctx, "Streaming complete for group: %v", group)
	return count, nil
}
开发者ID:dgraph-io,项目名称:dgraph,代码行数:61,代码来源:predicate.go

示例15: deletePrefix

func deletePrefix(ctx context.Context, client *clientv3.Client, key string) error {
	for ctx.Err() == nil {
		if _, err := client.Delete(ctx, key, clientv3.WithPrefix()); err == nil {
			return nil
		}
	}
	return ctx.Err()
}
开发者ID:pulcy,项目名称:vault-monkey,代码行数:8,代码来源:watcher.go


注:本文中的context.Context.Err方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。