當前位置: 首頁>>代碼示例>>Golang>>正文


Golang datastore.NewClient函數代碼示例

本文整理匯總了Golang中cloud/google/com/go/datastore.NewClient函數的典型用法代碼示例。如果您正苦於以下問題:Golang NewClient函數的具體用法?Golang NewClient怎麽用?Golang NewClient使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了NewClient函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: ExampleClient_Put_flatten

func ExampleClient_Put_flatten() {
	ctx := context.Background()
	client, err := datastore.NewClient(ctx, "project-id")
	if err != nil {
		log.Fatal(err)
	}

	type Animal struct {
		Name  string
		Type  string
		Breed string
	}

	type Human struct {
		Name   string
		Height int
		Pet    Animal `datastore:",flatten"`
	}

	newKey := datastore.IncompleteKey("Human", nil)
	_, err = client.Put(ctx, newKey, &Human{
		Name:   "Susan",
		Height: 67,
		Pet: Animal{
			Name:  "Fluffy",
			Type:  "Cat",
			Breed: "Sphynx",
		},
	})
	if err != nil {
		log.Fatal(err)
	}
}
開發者ID:trythings,項目名稱:trythings,代碼行數:33,代碼來源:example_test.go

示例2: NewResultDataRepo

// NewResultDataRepo - return new instance of the ResultDataRepo
func NewResultDataRepo(limit int, autoResize bool, symbol string, r *http.Request) ResultDataRepo {
	var ctx context.Context
	if r != nil {
		ctx = appengine.NewContext(r)
	} else {
		ctx = context.Background()
	}

	client, err := datastore.NewClient(ctx, projectID)
	if err != nil {
		log.Fatal(err)
	}

	rr := new(resultDataRepo)
	rr.pipe = make(chan commandResultData)
	rr.symbol = symbol
	rr.limit = limit
	rr.autoResize = autoResize == true
	rr.client = client

	if err := rr.loadStartResultData(); err != nil {
		log.Fatal(err)
	}

	go rr.run()
	return rr
}
開發者ID:rutmir,項目名稱:pr.optima,代碼行數:28,代碼來源:resultsRepo.go

示例3: NewEfficiencyRepo

// NewEfficiencyRepo return instance of the EfficiencyRepo
func NewEfficiencyRepo(trainType, symbol string, rangesCount, limit, frame int32, r *http.Request) EfficiencyRepo {
	// todo: switch from http.Request to context.Context
	var ctx context.Context
	if r != nil {
		ctx = appengine.NewContext(r)
	} else {
		ctx = context.Background()
	}

	client, err := datastore.NewClient(ctx, projectID)
	if err != nil {
		log.Fatal(err)
	}

	rr := new(efficiencyRepo)
	rr.pipe = make(chan commandEfficiency)
	rr.symbol = symbol
	rr.trainType = trainType
	rr.limit = limit
	rr.frame = frame
	rr.rangesCount = rangesCount
	rr.client = client

	if err := rr.loadStartEfficiency(); err != nil {
		log.Fatal(err)
	}

	go rr.run()
	return rr
}
開發者ID:rutmir,項目名稱:pr.optima,代碼行數:31,代碼來源:efficiencyRepo.go

示例4: ExampleClient_Put

func ExampleClient_Put() {
	ctx := context.Background()
	client, err := datastore.NewClient(ctx, "project-id")
	if err != nil {
		// TODO: Handle error.
	}

	type Article struct {
		Title       string
		Description string
		Body        string `datastore:",noindex"`
		Author      *datastore.Key
		PublishedAt time.Time
	}
	newKey := datastore.IncompleteKey("Article", nil)
	_, err = client.Put(ctx, newKey, &Article{
		Title:       "The title of the article",
		Description: "The description of the article...",
		Body:        "...",
		Author:      datastore.NameKey("Author", "jbd", nil),
		PublishedAt: time.Now(),
	})
	if err != nil {
		// TODO: Handle error.
	}
}
開發者ID:trythings,項目名稱:trythings,代碼行數:26,代碼來源:example_test.go

示例5: New

// New - return new instance of repo
func New(limit int, autoResize bool, r *http.Request) RateRepo {
	_limit = limit
	_autoResize = autoResize == true

	var ctx context.Context
	if r != nil {
		ctx = appengine.NewContext(r)
		//_ctx = ctx
	} else {
		ctx = context.Background()
	}

	client, err := datastore.NewClient(ctx, projectID)
	if err != nil {
		log.Fatal(err)
	}
	_client = client

	if err := loadStartRates(); err != nil {
		log.Fatal(err)
	}

	rr := make(rateRepo)
	go rr.run()
	return rr
}
開發者ID:rutmir,項目名稱:pr.optima,代碼行數:27,代碼來源:ratesRepo.go

示例6: Example_serviceAccount

func Example_serviceAccount() {
	// Warning: The better way to use service accounts is to set GOOGLE_APPLICATION_CREDENTIALS
	// and use the Application Default Credentials.
	ctx := context.Background()
	// Use a JSON key file associated with a Google service account to
	// authenticate and authorize.
	// Go to https://console.developers.google.com/permissions/serviceaccounts to create
	// and download a service account key for your project.
	//
	// Note: The example uses the datastore client, but the same steps apply to
	// the other client libraries underneath this package.
	key, err := ioutil.ReadFile("/path/to/service-account-key.json")
	if err != nil {
		// TODO: handle error.
	}
	cfg, err := google.JWTConfigFromJSON(key, datastore.ScopeDatastore)
	if err != nil {
		// TODO: handle error.
	}
	client, err := datastore.NewClient(
		ctx, "project-id", option.WithTokenSource(cfg.TokenSource(ctx)))
	if err != nil {
		// TODO: handle error.
	}
	// Use the client.
	_ = client
}
開發者ID:camlistore,項目名稱:camlistore,代碼行數:27,代碼來源:authexample_test.go

示例7: _getRatesKeys

func _getRatesKeys(r *http.Request, jsonKey []byte, unixtime int64) <-chan keyResult {
	out := make(chan keyResult)
	go func() {
		defer close(out)
		var ctx context.Context
		if r != nil {
			ctx = appengine.NewContext(r)
		} else {
			ctx = context.Background()
		}

		client, err := datastore.NewClient(ctx, "rp-optima")
		if err != nil {
			out <- keyResult{error: err}
			return
		}

		/*if keys, err := client.GetAll(ctx, datastore.NewQuery("ResultData").Filter("timestamp<", unixtime).KeysOnly(), nil); err != nil {
			out <- keyResult{error:err}
			return
		}else {
			out <- keyResult{keys:keys}
		}*/
		if keys, err := client.GetAll(ctx, datastore.NewQuery("Rate").Filter("id<", unixtime).KeysOnly(), nil); err != nil {
			out <- keyResult{error: err}
		} else {
			out <- keyResult{keys: keys}
		}
	}()
	return out
}
開發者ID:rutmir,項目名稱:pr.optima,代碼行數:31,代碼來源:repoInit.go

示例8: ExampleCommit_Key

func ExampleCommit_Key() {
	ctx := context.Background()
	client, err := datastore.NewClient(ctx, "")
	if err != nil {
		// TODO: Handle error.
	}
	var pk1, pk2 *datastore.PendingKey
	// Create two posts in a single transaction.
	commit, err := client.RunInTransaction(ctx, func(tx *datastore.Transaction) error {
		var err error
		pk1, err = tx.Put(datastore.IncompleteKey("Post", nil), &Post{Title: "Post 1", PublishedAt: time.Now()})
		if err != nil {
			return err
		}
		pk2, err = tx.Put(datastore.IncompleteKey("Post", nil), &Post{Title: "Post 2", PublishedAt: time.Now()})
		if err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		// TODO: Handle error.
	}
	// Now pk1, pk2 are valid PendingKeys. Let's convert them into real keys
	// using the Commit object.
	k1 := commit.Key(pk1)
	k2 := commit.Key(pk2)
	fmt.Println(k1, k2)
}
開發者ID:trythings,項目名稱:trythings,代碼行數:29,代碼來源:example_test.go

示例9: ExampleIterator_Cursor

func ExampleIterator_Cursor() {
	ctx := context.Background()
	client, _ := datastore.NewClient(ctx, "my-proj")
	cursorStr := ""
	// [START cursor_paging]
	const pageSize = 5
	query := datastore.NewQuery("Tasks").Limit(pageSize)
	if cursorStr != "" {
		cursor, err := datastore.DecodeCursor(cursorStr)
		if err != nil {
			log.Fatalf("Bad cursor %q: %v", cursorStr, err)
		}
		query = query.Start(cursor)
	}

	// Read the tasks.
	var tasks []Task
	var task Task
	it := client.Run(ctx, query)
	_, err := it.Next(&task)
	for err == nil {
		tasks = append(tasks, task)
		_, err = it.Next(&task)
	}
	if err != datastore.Done {
		log.Fatalf("Failed fetching results: %v", err)
	}

	// Get the cursor for the next page of results.
	nextCursor, err := it.Cursor()
	// [END cursor_paging]
	_ = err        // Check the error.
	_ = nextCursor // Use nextCursor.String as the next page's token.
}
開發者ID:camlistore,項目名稱:camlistore,代碼行數:34,代碼來源:examples_test.go

示例10: ExampleClient_PutMulti

func ExampleClient_PutMulti() {
	ctx := context.Background()
	client, _ := datastore.NewClient(ctx, "my-proj")
	// [START batch_upsert]
	tasks := []*Task{
		{
			Category:    "Personal",
			Done:        false,
			Priority:    4,
			Description: "Learn Cloud Datastore",
		},
		{
			Category:    "Personal",
			Done:        false,
			Priority:    5,
			Description: "Integrate Cloud Datastore",
		},
	}
	keys := []*datastore.Key{
		datastore.NewIncompleteKey(ctx, "Task", nil),
		datastore.NewIncompleteKey(ctx, "Task", nil),
	}

	keys, err := client.PutMulti(ctx, keys, tasks)
	// [END batch_upsert]
	_ = err  // Make sure you check err.
	_ = keys // keys now has the complete keys for the newly stored tasks.
}
開發者ID:camlistore,項目名稱:camlistore,代碼行數:28,代碼來源:examples_test.go

示例11: ExampleIterator_Cursor

func ExampleIterator_Cursor() {
	ctx := context.Background()
	client, err := datastore.NewClient(ctx, "project-id")
	if err != nil {
		// TODO: Handle error.
	}
	it := client.Run(ctx, datastore.NewQuery("Post"))
	for {
		var p Post
		_, err := it.Next(&p)
		if err == iterator.Done {
			break
		}
		if err != nil {
			// TODO: Handle error.
		}
		fmt.Println(p)
		cursor, err := it.Cursor()
		if err != nil {
			// TODO: Handle error.
		}
		// When printed, a cursor will display as a string that can be passed
		// to datastore.NewCursor.
		fmt.Printf("to resume with this post, use cursor %s\n", cursor)
	}
}
開發者ID:trythings,項目名稱:trythings,代碼行數:26,代碼來源:example_test.go

示例12: Example_Transaction

func Example_Transaction() {
	ctx := context.Background()
	client, _ := datastore.NewClient(ctx, "my-proj")
	var to, from *datastore.Key
	// [START transactional_update]
	type BankAccount struct {
		Balance int
	}

	const amount = 50
	keys := []*datastore.Key{to, from}
	tx, err := client.NewTransaction(ctx)
	if err != nil {
		log.Fatalf("client.NewTransaction: %v", err)
	}
	accs := make([]BankAccount, 2)
	if err := tx.GetMulti(keys, accs); err != nil {
		tx.Rollback()
		log.Fatalf("tx.GetMulti: %v", err)
	}
	accs[0].Balance += amount
	accs[1].Balance -= amount
	if _, err := tx.PutMulti(keys, accs); err != nil {
		tx.Rollback()
		log.Fatalf("tx.PutMulti: %v", err)
	}
	if _, err = tx.Commit(); err != nil {
		log.Fatalf("tx.Commit: %v", err)
	}
	// [END transactional_update]
}
開發者ID:camlistore,項目名稱:camlistore,代碼行數:31,代碼來源:examples_test.go

示例13: ExampleQuery

func ExampleQuery() {
	ctx := context.Background()
	client, err := datastore.NewClient(ctx, "project-id")
	if err != nil {
		log.Fatal(err)
	}

	// Count the number of the post entities.
	q := datastore.NewQuery("Post")
	n, err := client.Count(ctx, q)
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("There are %d posts.", n)

	// List the posts published since yesterday.
	yesterday := time.Now().Add(-24 * time.Hour)
	q = datastore.NewQuery("Post").Filter("PublishedAt >", yesterday)
	it := client.Run(ctx, q)
	// Use the iterator.
	_ = it

	// Order the posts by the number of comments they have recieved.
	datastore.NewQuery("Post").Order("-Comments")

	// Start listing from an offset and limit the results.
	datastore.NewQuery("Post").Offset(20).Limit(10)
}
開發者ID:rawlingsj,項目名稱:gofabric8,代碼行數:28,代碼來源:example_test.go

示例14: ExampleClient_RunInTransaction

func ExampleClient_RunInTransaction() {
	ctx := context.Background()
	client, err := datastore.NewClient(ctx, "project-id")
	if err != nil {
		// TODO: Handle error.
	}

	// Increment a counter.
	// See https://cloud.google.com/appengine/articles/sharding_counters for
	// a more scalable solution.
	type Counter struct {
		Count int
	}

	var count int
	key := datastore.NameKey("Counter", "singleton", nil)
	_, err = client.RunInTransaction(ctx, func(tx *datastore.Transaction) error {
		var x Counter
		if err := tx.Get(key, &x); err != nil && err != datastore.ErrNoSuchEntity {
			return err
		}
		x.Count++
		if _, err := tx.Put(key, &x); err != nil {
			return err
		}
		count = x.Count
		return nil
	})
	if err != nil {
		// TODO: Handle error.
	}
	// The value of count is only valid once the transaction is successful
	// (RunInTransaction has returned nil).
	fmt.Printf("Count=%d\n", count)
}
開發者ID:trythings,項目名稱:trythings,代碼行數:35,代碼來源:example_test.go

示例15: ExampleNewClient

func ExampleNewClient() {
	ctx := context.Background()
	client, err := datastore.NewClient(ctx, "project-id")
	if err != nil {
		// TODO: Handle error.
	}
	_ = client // TODO: Use client.
}
開發者ID:trythings,項目名稱:trythings,代碼行數:8,代碼來源:example_test.go


注:本文中的cloud/google/com/go/datastore.NewClient函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。