Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 

242 rader
4.9 KiB

  1. // Copyright 2017 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // This file holds samples that are embedded into README.md.
  15. // This file has to compile, but need not execute.
  16. // If it fails to compile, fix it, then run `make` to regenerate README.md.
  17. package readme
  18. import (
  19. "fmt"
  20. "io/ioutil"
  21. "log"
  22. "time"
  23. "cloud.google.com/go/bigquery"
  24. "cloud.google.com/go/datastore"
  25. "cloud.google.com/go/logging"
  26. "cloud.google.com/go/pubsub"
  27. "cloud.google.com/go/spanner"
  28. "cloud.google.com/go/storage"
  29. "golang.org/x/net/context"
  30. "golang.org/x/oauth2"
  31. "google.golang.org/api/iterator"
  32. "google.golang.org/api/option"
  33. )
  34. var ctx context.Context
  35. const END = 0
  36. func auth() {
  37. //[ auth
  38. client, err := storage.NewClient(ctx)
  39. //]
  40. _ = client
  41. _ = err
  42. }
  43. func auth2() {
  44. //[ auth-JSON
  45. client, err := storage.NewClient(ctx, option.WithServiceAccountFile("path/to/keyfile.json"))
  46. //]
  47. _ = client
  48. _ = err
  49. }
  50. func auth3() {
  51. var ELLIPSIS oauth2.TokenSource
  52. //[ auth-ts
  53. tokenSource := ELLIPSIS
  54. client, err := storage.NewClient(ctx, option.WithTokenSource(tokenSource))
  55. //]
  56. _ = client
  57. _ = err
  58. }
  59. func datastoreSnippets() {
  60. //[ datastore-1
  61. client, err := datastore.NewClient(ctx, "my-project-id")
  62. if err != nil {
  63. log.Fatal(err)
  64. }
  65. //]
  66. //[ datastore-2
  67. type Post struct {
  68. Title string
  69. Body string `datastore:",noindex"`
  70. PublishedAt time.Time
  71. }
  72. keys := []*datastore.Key{
  73. datastore.NameKey("Post", "post1", nil),
  74. datastore.NameKey("Post", "post2", nil),
  75. }
  76. posts := []*Post{
  77. {Title: "Post 1", Body: "...", PublishedAt: time.Now()},
  78. {Title: "Post 2", Body: "...", PublishedAt: time.Now()},
  79. }
  80. if _, err := client.PutMulti(ctx, keys, posts); err != nil {
  81. log.Fatal(err)
  82. }
  83. //]
  84. }
  85. func storageSnippets() {
  86. //[ storage-1
  87. client, err := storage.NewClient(ctx)
  88. if err != nil {
  89. log.Fatal(err)
  90. }
  91. //]
  92. //[ storage-2
  93. // Read the object1 from bucket.
  94. rc, err := client.Bucket("bucket").Object("object1").NewReader(ctx)
  95. if err != nil {
  96. log.Fatal(err)
  97. }
  98. defer rc.Close()
  99. body, err := ioutil.ReadAll(rc)
  100. if err != nil {
  101. log.Fatal(err)
  102. }
  103. //]
  104. _ = body
  105. }
  106. func pubsubSnippets() {
  107. //[ pubsub-1
  108. client, err := pubsub.NewClient(ctx, "project-id")
  109. if err != nil {
  110. log.Fatal(err)
  111. }
  112. //]
  113. const ELLIPSIS = 0
  114. //[ pubsub-2
  115. // Publish "hello world" on topic1.
  116. topic := client.Topic("topic1")
  117. res := topic.Publish(ctx, &pubsub.Message{
  118. Data: []byte("hello world"),
  119. })
  120. // The publish happens asynchronously.
  121. // Later, you can get the result from res:
  122. _ = ELLIPSIS
  123. msgID, err := res.Get(ctx)
  124. if err != nil {
  125. log.Fatal(err)
  126. }
  127. // Use a callback to receive messages via subscription1.
  128. sub := client.Subscription("subscription1")
  129. err = sub.Receive(ctx, func(ctx context.Context, m *pubsub.Message) {
  130. fmt.Println(m.Data)
  131. m.Ack() // Acknowledge that we've consumed the message.
  132. })
  133. if err != nil {
  134. log.Println(err)
  135. }
  136. //]
  137. _ = msgID
  138. }
  139. func bqSnippets() {
  140. //[ bq-1
  141. c, err := bigquery.NewClient(ctx, "my-project-ID")
  142. if err != nil {
  143. // TODO: Handle error.
  144. }
  145. //]
  146. //[ bq-2
  147. // Construct a query.
  148. q := c.Query(`
  149. SELECT year, SUM(number)
  150. FROM [bigquery-public-data:usa_names.usa_1910_2013]
  151. WHERE name = "William"
  152. GROUP BY year
  153. ORDER BY year
  154. `)
  155. // Execute the query.
  156. it, err := q.Read(ctx)
  157. if err != nil {
  158. // TODO: Handle error.
  159. }
  160. // Iterate through the results.
  161. for {
  162. var values []bigquery.Value
  163. err := it.Next(&values)
  164. if err == iterator.Done {
  165. break
  166. }
  167. if err != nil {
  168. // TODO: Handle error.
  169. }
  170. fmt.Println(values)
  171. }
  172. //]
  173. }
  174. func loggingSnippets() {
  175. //[ logging-1
  176. ctx := context.Background()
  177. client, err := logging.NewClient(ctx, "my-project")
  178. if err != nil {
  179. // TODO: Handle error.
  180. }
  181. //]
  182. //[ logging-2
  183. logger := client.Logger("my-log")
  184. logger.Log(logging.Entry{Payload: "something happened!"})
  185. //]
  186. //[ logging-3
  187. err = client.Close()
  188. if err != nil {
  189. // TODO: Handle error.
  190. }
  191. //]
  192. }
  193. func spannerSnippets() {
  194. //[ spanner-1
  195. client, err := spanner.NewClient(ctx, "projects/P/instances/I/databases/D")
  196. if err != nil {
  197. log.Fatal(err)
  198. }
  199. //]
  200. //[ spanner-2
  201. // Simple Reads And Writes
  202. _, err = client.Apply(ctx, []*spanner.Mutation{
  203. spanner.Insert("Users",
  204. []string{"name", "email"},
  205. []interface{}{"alice", "a@example.com"})})
  206. if err != nil {
  207. log.Fatal(err)
  208. }
  209. row, err := client.Single().ReadRow(ctx, "Users",
  210. spanner.Key{"alice"}, []string{"email"})
  211. if err != nil {
  212. log.Fatal(err)
  213. }
  214. //]
  215. _ = row
  216. }