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


Golang context.Background函数代码示例

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


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

示例1: TestCustomPrefix

func TestCustomPrefix(t *testing.T) {
	Convey("Given the App running with PREFIX", t, func() {
		uc := make(chan string, 0)
		bc := make(chan string, 0)
		f := Flag
		f.Prefix = "BETA"
		ctx, _ := context.WithCancel(context.Background())
		ctx = context.WithValue(ctx, "Flag", f)
		app := NewApp(ctx, GetMockPerformJsonPost(uc, bc))
		v1httpapi := V1HttpApi{
			App: app,
		}
		v1httpapi.registerRoutes(app.Router)

		Convey("When posting a message", func() {
			ts := httptest.NewServer(app.Router)
			defer ts.Close()
			post_body := bytes.NewReader([]byte(""))
			http.Post(ts.URL+"/log/fakelevel/fakecategory/fakeslug/", "application/json", post_body)

			So(<-uc, ShouldEqual, "http://"+f.ApiEndPoint+"/v1/log/bulk/")
			body := <-bc
			So(body, ShouldContainSubstring, "\"__prefix\":\"BETA\"")
			So(body, ShouldContainSubstring, "\"__category\":\"fakecategory\"")
			So(body, ShouldContainSubstring, "\"__level\":\"fakelevel\"")
			So(body, ShouldContainSubstring, "\"__namespace\"")
			So(body, ShouldContainSubstring, "\"__slug\":\"fakeslug\"")
		})

	})

	Convey("Given the App running WITHOUT prefix", t, func() {
		uc := make(chan string, 0)
		bc := make(chan string, 0)
		f := Flag
		ctx, _ := context.WithCancel(context.Background())
		ctx = context.WithValue(ctx, "Flag", f)
		app := NewApp(ctx, GetMockPerformJsonPost(uc, bc))
		v1httpapi := V1HttpApi{
			App: app,
		}
		v1httpapi.registerRoutes(app.Router)

		Convey("When posting a message", func() {
			ts := httptest.NewServer(app.Router)
			defer ts.Close()
			post_body := bytes.NewReader([]byte(""))
			http.Post(ts.URL+"/log/fakelevel/fakecategory/fakeslug/", "application/json", post_body)

			So(<-uc, ShouldEqual, "http://"+f.ApiEndPoint+"/v1/log/bulk/")
			body := <-bc
			So(body, ShouldNotContainSubstring, "\"__prefix\"")
			So(body, ShouldContainSubstring, "\"__category\":\"fakecategory\"")
			So(body, ShouldContainSubstring, "\"__level\":\"fakelevel\"")
			So(body, ShouldContainSubstring, "\"__namespace\"")
			So(body, ShouldContainSubstring, "\"__slug\":\"fakeslug\"")
		})

	})
}
开发者ID:KSCTECHNOLOGIES,项目名称:uberlog-proxy,代码行数:60,代码来源:http_api_test.go

示例2: handleSearch

// handleSearch handles URLs like /search?q=golang&timeout=1s by forwarding the
// query to google.Search. If the query param includes timeout, the search is
// canceled after that duration elapses.
func handleSearch(w http.ResponseWriter, req *http.Request) {
	// ctx is the Context for this handler. Calling cancel closes the
	// ctx.Done channel, which is the cancellation signal for requests
	// started by this handler.
	var (
		ctx    context.Context
		cancel context.CancelFunc
	)
	timeout, err := time.ParseDuration(req.FormValue("timeout"))
	if err == nil {
		// The request has a timeout, so create a context that is
		// canceled automatically when the timeout expires.
		ctx, cancel = context.WithTimeout(context.Background(), timeout)
	} else {
		ctx, cancel = context.WithCancel(context.Background())
	}
	defer cancel() // Cancel ctx as soon as handleSearch returns.

	// Check the search query.
	query := req.FormValue("q")
	if query == "" {
		http.Error(w, "no query", http.StatusBadRequest)
		return
	}

	// Store the user IP in ctx for use by code in other packages.
	userIP, err := userip.FromRequest(req)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	ctx = userip.NewContext(ctx, userIP)

	// Run the Google search and print the results.
	start := time.Now()
	results, err := google.Search(ctx, query)
	elapsed := time.Since(start)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	if err := resultsTemplate.Execute(w, struct {
		Results          google.Results
		Timeout, Elapsed time.Duration
	}{
		Results: results,
		Timeout: timeout,
		Elapsed: elapsed,
	}); err != nil {
		log.Print(err)
		return
	}
}
开发者ID:bryanxu,项目名称:go-zh.blog,代码行数:56,代码来源:server.go

示例3: main

func main() {
	flag.Parse()
	runtime.GOMAXPROCS(runtime.NumCPU() - 1)

	laddr, _ := net.ResolveTCPAddr("tcp", ":"+port) // TODO(zog): flag
	l, err := net.ListenTCP("tcp", laddr)
	if err != nil {
		glog.Fatalf("net.ListenTCP: %v", err)
	}

	ctx := context.Background()

	glog.Infof("server start listen on: %s", laddr.String())
	for {
		tcpconn, err := l.AcceptTCP()
		if err != nil {
			glog.Errorf("Accept error, server stop (listen on:%s), err: %s",
				laddr.String(), err)
			break
		}

		go HandleConnection(ctx, tcpconn)
	}
	glog.Infof("server stop listen on: %s)", laddr.String())
}
开发者ID:zoglee,项目名称:netty,代码行数:25,代码来源:main.go

示例4: TestBlobstore

func TestBlobstore(t *testing.T) {
	db := datasql.MustConnect("sqlite3", ":memory:")
	bs := New(db)

	g := goblin.Goblin(t)
	g.Describe("Blobstore", func() {

		// before each test be sure to purge the blob
		// table data from the database.
		g.Before(func() {
			db.Exec("DELETE FROM blobs")
		})

		g.It("Should Put a Blob", func() {
			err := bs.Put("foo", []byte("bar"))
			g.Assert(err == nil).IsTrue()
		})

		g.It("Should Put a Blob reader", func() {
			var buf bytes.Buffer
			buf.Write([]byte("bar"))
			err := bs.PutReader("foo", &buf)
			g.Assert(err == nil).IsTrue()
		})

		g.It("Should Overwrite a Blob", func() {
			bs.Put("foo", []byte("bar"))
			bs.Put("foo", []byte("baz"))
			blob, err := bs.Get("foo")
			g.Assert(err == nil).IsTrue()
			g.Assert(string(blob)).Equal("baz")
		})

		g.It("Should Get a Blob", func() {
			bs.Put("foo", []byte("bar"))
			blob, err := bs.Get("foo")
			g.Assert(err == nil).IsTrue()
			g.Assert(string(blob)).Equal("bar")
		})

		g.It("Should Get a Blob reader", func() {
			bs.Put("foo", []byte("bar"))
			r, _ := bs.GetReader("foo")
			blob, _ := ioutil.ReadAll(r)
			g.Assert(string(blob)).Equal("bar")
		})

		g.It("Should Del a Blob", func() {
			bs.Put("foo", []byte("bar"))
			err := bs.Del("foo")
			g.Assert(err == nil).IsTrue()
		})

		g.It("Should create a Context", func() {
			c := NewContext(context.Background(), db)
			b := blobstore.FromContext(c).(*Blobstore)
			g.Assert(b.DB).Equal(db)
		})
	})
}
开发者ID:drone,项目名称:drone-dart,代码行数:60,代码来源:blobstore_test.go

示例5: TestHTTP

func TestHTTP(t *testing.T) {
	ctx := context.Background()
	once.Do(startServer)
	testHTTPRPC(ctx, t, "")
	newOnce.Do(startNewServer)
	testHTTPRPC(ctx, t, newHttpPath)
}
开发者ID:henryanand,项目名称:vitess,代码行数:7,代码来源:server_test.go

示例6: checkPermissions

func (qre *QueryExecutor) checkPermissions() {
	// Skip permissions check if we have a background context.
	if qre.ctx == context.Background() {
		return
	}

	// Blacklist
	ci := callinfo.FromContext(qre.ctx)
	action, desc := qre.plan.Rules.getAction(ci.RemoteAddr(), ci.Username(), qre.bindVars)
	switch action {
	case QR_FAIL:
		panic(NewTabletError(FAIL, "Query disallowed due to rule: %s", desc))
	case QR_FAIL_RETRY:
		panic(NewTabletError(RETRY, "Query disallowed due to rule: %s", desc))
	}

	// ACLs
	if !qre.plan.Authorized.IsMember(ci.Username()) {
		errStr := fmt.Sprintf("table acl error: %q cannot run %v on table %q", ci.Username(), qre.plan.PlanId, qre.plan.TableName)
		if qre.qe.strictTableAcl {
			panic(NewTabletError(FAIL, "%s", errStr))
		}
		qre.qe.accessCheckerLogger.Errorf("%s", errStr)
	}
}
开发者ID:henryanand,项目名称:vitess,代码行数:25,代码来源:query_executor.go

示例7: main

func main() {
	const numRequests = 3
	// create a channel to capture our results
	forecasts := make(chan *openweathermap.Forecast, numRequests)

	// create our channel of requests
	requests := make(chan par.RequestFunc, numRequests)
	requests <- findById(4288809, forecasts) // Covington, VA
	requests <- findById(4288809, forecasts)
	requests <- findById(4140963, forecasts) // DC
	close(requests)                          // important to remember to close the channel

	// resolver := par.Requests(requests).WithRedundancy(1)
	resolver := par.Requests(requests).WithConcurrency(numRequests)
	ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
	// ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
	err := resolver.DoWithContext(ctx)
	cancel()
	ok(err)

	// the forecasts channel now contains all our forecasts
	close(forecasts)
	cities := map[string]*openweathermap.Forecast{}
	for forecast := range forecasts {
		cities[forecast.Name] = forecast
	}
}
开发者ID:cleesmith,项目名称:golang_learning,代码行数:27,代码来源:weather.go

示例8: IsHealthy

// IsHealthy returns nil if the query service is healthy (able to
// connect to the database and serving traffic) or an error explaining
// the unhealthiness otherwise.
func IsHealthy() error {
	return SqlQueryRpcService.Execute(
		context.Background(),
		&proto.Query{Sql: "select 1 from dual", SessionId: SqlQueryRpcService.sessionId},
		new(mproto.QueryResult),
	)
}
开发者ID:henryanand,项目名称:vitess,代码行数:10,代码来源:queryctl.go

示例9: BasicMngrHandler

// BasicMngrHandler can be use in "manager" ServeHTTP after initital required interface like
// authmodel.UserManager, authmodel.GroupManager, conf.Configurator...etc
func BasicMngrHandler(authCtx *AuthContext, rw http.ResponseWriter, req *http.Request, cond *Condition, fn HandleFunc) {
	var cancel context.CancelFunc
	authCtx.Context, cancel = context.WithTimeout(context.Background(), HandleTimeout)
	defer cancel()

	authCtx.req = req
	token := strings.TrimPrefix(req.Header.Get("Authorization"), "Bearer ")
	authCtx.saveToken(token)
	authCtx.saveId(mux.Vars(req)["user_id"])

	authCtx.Notifications = DEFAULT_NOTIFICATOR
	authCtx.Logs = DEFAULT_LOGGER

	rw.Header().Set("Content-Type", "application/json; charset=utf-8")
	if cond.RequiredPri != nil || cond.Owner {
		_, err := authCtx.ValidCurrentUser(cond.Owner, cond.RequiredPri)
		if err != nil {
			JSONError(rw, err.Error(), http.StatusForbidden)
			return
		}
	}

	status, err := fn(authCtx, rw, req)
	if err != nil {
		authCtx.Logs.Errorf("HTTP %d: %q", status, err)
		JSONError(rw, err.Error(), status)
	}
}
开发者ID:kidstuff,项目名称:auth,代码行数:30,代码来源:auth.go

示例10: TestServeRequest

func TestServeRequest(t *testing.T) {
	ctx := context.Background()
	once.Do(startServer)
	testServeRequest(ctx, t, nil)
	newOnce.Do(startNewServer)
	testServeRequest(ctx, t, newServer)
}
开发者ID:henryanand,项目名称:vitess,代码行数:7,代码来源:server_test.go

示例11: TestRPC

func TestRPC(t *testing.T) {
	ctx := context.Background()
	once.Do(startServer)
	testRPC(ctx, t, serverAddr)
	newOnce.Do(startNewServer)
	testRPC(ctx, t, newServerAddr)
}
开发者ID:henryanand,项目名称:vitess,代码行数:7,代码来源:server_test.go

示例12: main

func main() {
	flag.Parse()
	client, err := zrpc.Dial("tcp://127.0.0.1:1337")
	if err != nil {
		log.Fatal(err)
	}

	start := time.Now()
	runs := 10000

	for i := 0; i < runs; i++ {
		// Create the request and response
		req := &pb.ReverseRequest{
			NormalString: proto.String("teststring"),
		}
		resp := &pb.ReverseResponse{}

		// Create the context and pass request timeout and service name
		ctx, _ := context.WithTimeout(context.Background(), time.Second*1)
		ctx = zrpc.NewServiceNameContext(ctx, "reverseservice")
		if err := client.Call(ctx, req, resp); err != nil {
			log.Println("error:", err)
		} else {
			log.Println("received:", resp)
		}

		log.Printf("%d goroutines", runtime.NumGoroutine())
		// time.Sleep(time.Millisecond * 500)
	}

	totalTime := time.Since(start)

	log.Printf("Performed %d reqs in %s (avg %s)", runs, totalTime, totalTime/time.Duration(runs))
}
开发者ID:gust1n,项目名称:zrpc,代码行数:34,代码来源:client.go

示例13: TestNewAndFromContext

func TestNewAndFromContext(t *testing.T) {
	newl := log.WithField("key", "value")
	ctx := NewContext(context.Background(), newl)
	froml, ok := FromContext(ctx)
	if !ok || newl != froml {
		t.Error("context does not contain tcplog")
	}
}
开发者ID:jpittis,项目名称:pubsub-proto,代码行数:8,代码来源:tcplog_test.go

示例14: ServeHTTP

func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	ctx := context.Background()
	ctx, cancel := context.WithTimeout(ctx, RequestTimeout)
	defer cancel()
	ctx = reqid.NewContext(ctx, reqid.New())
	log.Printf(ctx, "http request: remote=%q method=%q url=%q",
		r.RemoteAddr, r.Method, r.URL)
	h(ctx, w, r)
}
开发者ID:shalecraig,项目名称:livegrep,代码行数:9,代码来源:server.go

示例15: SetupIpfs

func SetupIpfs() (*core.IpfsNode, error) {
	// Assume the user has run 'ipfs init'
	r := fsrepo.At("~/.ipfs")
	if err := r.Open(); err != nil {
		return nil, err
	}

	builder := core.NewNodeBuilder().Online().SetRepo(r)
	return builder.Build(context.Background())
}
开发者ID:bcomnes,项目名称:examples,代码行数:10,代码来源:demo.go


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