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


Golang context.Context类代码示例

本文整理汇总了Golang中code/google/com/p/go/net/context.Context的典型用法代码示例。如果您正苦于以下问题:Golang Context类的具体用法?Golang Context怎么用?Golang Context使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


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

示例1: Work

func Work(ctx context.Context, errc chan<- error, sysfd int, reqc <-chan *Request, inreqc <-chan *Request, rspc chan<- *Response) {
	go func() {
		defer func() {
			glog.Infof("Work is stoped")
		}()

		for {
			var rsp *Response
			var err error
			select {
			case <-ctx.Done():
				glog.Infof("Done for Work")
				return

			case req := <-reqc:
				if rsp, err = work(req); err != nil {
					errc <- fmt.Errorf("in Work req channel: %s", err)
					return
				}
				rspc <- rsp

			case req := <-inreqc:
				var rsp *Response
				if rsp, err = work(req); err != nil {
					errc <- fmt.Errorf("in Work inner req channel: %s", err)
					return
				}
				rspc <- rsp
			}
		}
	}()
}
开发者ID:zoglee,项目名称:netty,代码行数:32,代码来源:work.go

示例2: newGateway

// newGateway does all the gateway initialisation once the gateway name is known
func (g *Gateway) newGateway(ctx context.Context, certificateFile, keyFile string) (*Gateway, error) {

	gips, err := lookupGateway(g.gateway)
	if nil != err {
		return nil, err
	}
	ipMap := map[string]int8{}
	for _, ip := range gips {
		ipMap[ip] = 0
	}
	g.gips = ips{ipMap: ipMap}
	g.errors = make(chan *PushNotificationRequestResponse)
	g.senders = []*Sender{}
	// TODO GSE: Enable the possibilty to choose the number of senders
	err = g.newSender(ctx, certificateFile, keyFile)
	if err != nil {
		return nil, err
	}
	go func() {
		for {
			select {
			case <-ctx.Done():
				return
			case pnrr := <-g.errors:
				if g.onError != nil {
					go g.onError(pnrr.Notification, pnrr.Response)
				}
			}
		}
	}()
	return g, nil
}
开发者ID:arnaud-lb,项目名称:apns,代码行数:33,代码来源:gateway.go

示例3: SetProfileImage

func (handler *HomeWebserviceHandler) SetProfileImage(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	user := ctx.Value(KeyUser).(*usecases.User)

	imgData, hndl, err := r.FormFile("File")
	if err != nil {
		handler.Webservice.Error(w, err)
		return
	}

	handler.Webservice.Log(fmt.Sprintf("Upload file %s", hndl.Filename))

	image, err := handler.ImageUtils.Load(imgData)
	if err != nil {
		handler.Webservice.Error(w, err)
		return
	}

	image = handler.ImageUtils.Resize(image, 192, 192)

	data, err := handler.ImageUtils.Save(image, ".png")

	err = handler.FileStore.Create(fmt.Sprintf("upload/profile_%d.png", user.Id), data)
	if err != nil {
		handler.Webservice.Error(w, err)
		return
	}

	if err != nil {
		handler.Webservice.Error(w, err)
		return
	}

	handler.Webservice.SendJson(w, setProfileImageResponse{Result: true})
}
开发者ID:janicduplessis,项目名称:projectgo,代码行数:34,代码来源:homewebservice.go

示例4: Send

func Send(ctx context.Context, errc chan<- error, sysfd int, tcpconn *net.TCPConn) (rspc chan *Response) {
	rspc = make(chan *Response, 10) // TODO(zog): is 10 a good number?

	go func() {
		defer func() {
			glog.Infof("Send is stoped")
		}()

		for {
			select {
			case <-ctx.Done():
				glog.Infof("Done for Send")
				return

			case rsp := <-rspc:
				if err := send(tcpconn, rsp); err != nil {
					errc <- fmt.Errorf("in Send: %s", err)
					return
				}
			}
		}
	}()

	return rspc
}
开发者ID:zoglee,项目名称:netty,代码行数:25,代码来源:send.go

示例5: getConn

// getConn reuses an existing connection if possible. Otherwise
// it returns a connection which it will save for future reuse.
// If it returns an error, retry will tell you if getConn can be retried.
// If the context has a deadline and exceeded, it returns error and no-retry immediately.
func (sdc *ShardConn) getConn(ctx context.Context) (conn tabletconn.TabletConn, endPoint topo.EndPoint, err error, retry bool) {
	sdc.mu.Lock()
	defer sdc.mu.Unlock()

	// fail-fast if deadline exceeded
	deadline, ok := ctx.Deadline()
	if ok {
		if time.Now().After(deadline) {
			return nil, topo.EndPoint{}, tabletconn.OperationalError("vttablet: deadline exceeded"), false
		}
	}

	if sdc.conn != nil {
		return sdc.conn, sdc.conn.EndPoint(), nil, false
	}

	endPoint, err = sdc.balancer.Get()
	if err != nil {
		return nil, topo.EndPoint{}, err, false
	}
	conn, err = tabletconn.GetDialer()(ctx, endPoint, sdc.keyspace, sdc.shard, sdc.timeout)
	if err != nil {
		sdc.balancer.MarkDown(endPoint.Uid, err.Error())
		return nil, endPoint, err, true
	}
	sdc.conn = conn
	return sdc.conn, endPoint, nil, false
}
开发者ID:henryanand,项目名称:vitess,代码行数:32,代码来源:shard_conn.go

示例6: transmitter

func transmitter(id string, ws *websocket.Conn, c chan *registrar.T, ctx context.Context, cancel context.CancelFunc) {
	var err error
	var data *registrar.T
	defer ws.Close()
	//defer close(c)
	defer cancel()
	defer registrar.RemoveConnection(id)
Loop:
	for {
		select {
		case data = <-c:
			err = websocket.JSON.Send(ws, *data)
			//websocket.Message.Send(ws, data.Msg)
			if err != nil {
				if !ws.IsClientConn() {
					log.Printf("transmitter closed\n")
				} else {
					log.Printf("transmitter error %v\n", err)
				}
				break Loop
			}
		case <-ctx.Done():
			log.Printf("transmitter closed")
			break Loop
		}
	}
}
开发者ID:mikechack,项目名称:wsrouter,代码行数:27,代码来源:server.go

示例7: HTTPRequest

// HTTPRequest returns the *http.Request associated with ctx using NewContext,
// if any.
func HTTPRequest(ctx context.Context) (*http.Request, bool) {
	// We cannot use ctx.(*wrapper).req to get the request because ctx may
	// be a Context derived from a *wrapper. Instead, we use Value to
	// access the request if it is anywhere up the Context tree.
	req, ok := ctx.Value(reqKey).(*http.Request)
	return req, ok
}
开发者ID:htee,项目名称:htee,代码行数:9,代码来源:context.go

示例8: Recv

func Recv(ctx context.Context, errc chan<- error, sysfd int, tcpconn *net.TCPConn) (reqc chan *Request) {
	reqc = make(chan *Request, 10) // TODO(zog): is 10 a good number?

	go func() {
		defer func() {
			glog.Infof("Recv is stoped")
		}()

		var req *Request
		var err error
		for {
			select {
			case <-ctx.Done():
				glog.Infof("Done for Recv")
				return

			default:
				if req, err = recv(tcpconn); err != nil {
					errc <- fmt.Errorf("in Recv: %s", err)
					return
				}
				reqc <- req
			}
		}
	}()

	return reqc
}
开发者ID:zoglee,项目名称:netty,代码行数:28,代码来源:recv.go

示例9: doSearch

func (s *server) doSearch(ctx context.Context, backend *Backend, q *client.Query) (*api.ReplySearch, error) {
	var cl client.Client
	var search client.Search
	var err error

	select {
	case cl = <-backend.Clients:
	case <-ctx.Done():
		return nil, ErrTimedOut
	}
	defer backend.CheckIn(cl)

	search, err = cl.Query(q)
	if err != nil {
		log.Printf(ctx, "error talking to backend err=%s", err)
		return nil, err
	}

	reply := &api.ReplySearch{Results: make([]*client.Result, 0)}

	for r := range search.Results() {
		reply.Results = append(reply.Results, r)
	}

	reply.Info, err = search.Close()
	if err != nil {
		return nil, err
	}
	return reply, nil
}
开发者ID:shalecraig,项目名称:livegrep,代码行数:30,代码来源:api.go

示例10: rpcCallTablet

// rpcCallTablet wil execute the RPC on the remote server.
func (client *GoRpcTabletManagerClient) rpcCallTablet(ctx context.Context, tablet *topo.TabletInfo, name string, args, reply interface{}) error {
	// create the RPC client, using ctx.Deadline if set, or no timeout.
	var connectTimeout time.Duration
	deadline, ok := ctx.Deadline()
	if ok {
		connectTimeout = deadline.Sub(time.Now())
		if connectTimeout < 0 {
			return fmt.Errorf("Timeout connecting to TabletManager.%v on %v", name, tablet.Alias)
		}
	}
	rpcClient, err := bsonrpc.DialHTTP("tcp", tablet.Addr(), connectTimeout, nil)
	if err != nil {
		return fmt.Errorf("RPC error for %v: %v", tablet.Alias, err.Error())
	}
	defer rpcClient.Close()

	// use the context Done() channel. Will handle context timeout.
	call := rpcClient.Go(ctx, "TabletManager."+name, args, reply, nil)
	select {
	case <-ctx.Done():
		return fmt.Errorf("Timeout waiting for TabletManager.%v to %v", name, tablet.Alias)
	case <-call.Done:
		if call.Error != nil {
			return fmt.Errorf("Remote error for %v: %v", tablet.Alias, call.Error.Error())
		} else {
			return nil
		}
	}
}
开发者ID:henryanand,项目名称:vitess,代码行数:30,代码来源:gorpc_client.go

示例11: Username

// Username accesses the authenticated username of the rpcwrap call connection in this context.
func Username(ctx context.Context) (user string, ok bool) {
	val := ctx.Value(usernameKey)
	if val == nil {
		return "", false
	}
	user, ok = val.(string)
	if !ok {
		return "", false
	}
	return user, ok
}
开发者ID:henryanand,项目名称:vitess,代码行数:12,代码来源:proto.go

示例12: RemoteAddr

// RemoteAddr accesses the remote address of the rpcwrap call connection in this context.
func RemoteAddr(ctx context.Context) (addr string, ok bool) {
	val := ctx.Value(remoteAddrKey)
	if val == nil {
		return "", false
	}
	addr, ok = val.(string)
	if !ok {
		return "", false
	}
	return addr, true
}
开发者ID:henryanand,项目名称:vitess,代码行数:12,代码来源:proto.go

示例13: NewReader

// NewReader creates a new io.ReadCloser to read the contents
// of the object.
func NewReader(ctx context.Context, bucket, name string) (io.ReadCloser, error) {
	c := ctx.Value(internal.Key(0)).(map[string]interface{})["http_client"].(*http.Client)
	resp, err := c.Get(fmt.Sprintf(templURLMedia, bucket, name))
	if err != nil {
		return nil, err
	}
	if resp.StatusCode == http.StatusNotFound {
		return nil, ErrObjectNotExists
	}
	return resp.Body, nil
}
开发者ID:qwo,项目名称:abelana-gcp,代码行数:13,代码来源:storage.go

示例14: SetUsername

// SetUsername sets the authenticated username associated with the rpcwrap call connection for this context.
// NOTE: For internal use by the rpcwrap library only. Contexts are supposed to be readonly, and
// this somewhat circumvents this intent.
func SetUsername(ctx context.Context, username string) (ok bool) {
	val := ctx.Value(usernameSlotKey)
	if val == nil {
		return false
	}
	slot, ok := val.(*string)
	if !ok {
		return false
	}
	*slot = username
	return true
}
开发者ID:henryanand,项目名称:vitess,代码行数:15,代码来源:proto.go

示例15: Send

// Send sends push notification to the APNs.
func (c *PersistentClient) Send(ctx context.Context, pn *PushNotification) *PushNotificationResponse {

	resp := NewPushNotificationResponse(pn)
	payload, err := pn.ToBytes()
	if err != nil {
		resp.Success = false
		resp.Error = err
		return resp
	}

	_, err = c.Write(payload)
	if err != nil {
		resp.Success = false
		resp.ResponseCommand = LocalResponseCommand
		resp.ResponseStatus = RetryPushNotificationStatus
		resp.Error = err
		return resp
	}
	log.Println("Sending push notification with ID", pn.Identifier)

	// This channel will contain the raw response
	// from Apple in the event of a failure.
	responseChannel := make(chan []byte, 1)
	go func() {
		buffer := make([]byte, 6)
		n, err := c.Read(buffer)
		if n != 6 && err != nil {
			buffer[0] = LocalResponseCommand
			e, ok := err.(net.Error)
			switch {
			case err == io.EOF: // Socket has been closed
				buffer[1] = RetryPushNotificationStatus
			case ok && e.Timeout(): // There is an error and it is a timeout
				buffer[1] = NoErrorsStatus
			default:
				buffer[1] = UnknownErrorStatus
			}
		}
		responseChannel <- buffer
	}()

	select {
	case <-ctx.Done():
		<-responseChannel // Wait for the read to end.
		resp.Success = false
		resp.ResponseCommand = LocalResponseCommand
		resp.ResponseStatus = CanceledPushNotificationStatus
		resp.Error = ctx.Err()
	case r := <-responseChannel:
		resp.FromRawAppleResponse(r)
	}
	return resp
}
开发者ID:arnaud-lb,项目名称:apns,代码行数:54,代码来源:persistentclient.go


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