當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。