Created
July 22, 2017 10:15
-
-
Save pyohei/114b5ea93ec429b1684ce0277a3de7e7 to your computer and use it in GitHub Desktop.
Access BigQuery with service account (golang).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//This is sample source code. | |
package main | |
import ( | |
"cloud.google.com/go/bigquery" | |
"fmt" | |
"golang.org/x/net/context" | |
"golang.org/x/oauth2/google" | |
bq "google.golang.org/api/bigquery/v2" | |
"google.golang.org/api/iterator" | |
"google.golang.org/api/option" | |
"os" | |
) | |
func main() { | |
json := os.Getenv("GOOGLE_APPLICATION_CREDENTIALS") | |
ctx := context.Background() | |
projectID := os.Getenv("BQ_ID") | |
jwtConfig, err := google.JWTConfigFromJSON([]byte(json), bq.BigqueryScope) | |
if err != nil { | |
fmt.Printf("Json load error: %v\n", err) | |
} | |
ts := jwtConfig.TokenSource(ctx) | |
client, err := bigquery.NewClient(ctx, projectID, option.WithTokenSource(ts)) | |
if err != nil { | |
fmt.Printf("Client create error: %v\n", err) | |
} | |
bqSql := " SELECT zipp.zip as zip, zipp.address as address FROM [zip.zip] zipp WHERE RAND() < 100/123920 limit 109 " | |
fmt.Println(bqSql) | |
q := client.Query(bqSql) | |
it, err := q.Read(ctx) | |
if err != nil { | |
fmt.Printf("Error2: %v\n", err) | |
} | |
for { | |
var values []bigquery.Value | |
err := it.Next(&values) | |
if err == iterator.Done { | |
break | |
} | |
if err != nil { | |
fmt.Printf("Error3: %v\n", err) | |
} | |
fmt.Printf(values[0].(string)) | |
fmt.Printf(values[1].(string)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I wrote this code for use bigquery from heroku.
If you want to know how to set up GCP and Heroku, read my blog.
However, this blog is written with Japanese... sorry.