dial.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. // Copyright 2015 Google Inc. All Rights Reserved.
  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. // Package transport supports network connections to HTTP and GRPC servers.
  15. // This package is not intended for use by end developers. Use the
  16. // google.golang.org/api/option package to configure API clients.
  17. package transport
  18. import (
  19. "errors"
  20. "fmt"
  21. "io/ioutil"
  22. "net/http"
  23. "golang.org/x/net/context"
  24. "golang.org/x/oauth2"
  25. "golang.org/x/oauth2/google"
  26. "google.golang.org/grpc"
  27. "google.golang.org/grpc/credentials"
  28. "google.golang.org/grpc/credentials/oauth"
  29. gtransport "google.golang.org/api/googleapi/transport"
  30. "google.golang.org/api/internal"
  31. "google.golang.org/api/option"
  32. )
  33. // NewHTTPClient returns an HTTP client for use communicating with a Google cloud
  34. // service, configured with the given ClientOptions. It also returns the endpoint
  35. // for the service as specified in the options.
  36. func NewHTTPClient(ctx context.Context, opts ...option.ClientOption) (*http.Client, string, error) {
  37. var o internal.DialSettings
  38. for _, opt := range opts {
  39. opt.Apply(&o)
  40. }
  41. if o.GRPCConn != nil {
  42. return nil, "", errors.New("unsupported gRPC connection specified")
  43. }
  44. // TODO(djd): Set UserAgent on all outgoing requests.
  45. if o.HTTPClient != nil {
  46. return o.HTTPClient, o.Endpoint, nil
  47. }
  48. if o.APIKey != "" {
  49. hc := &http.Client{
  50. Transport: &gtransport.APIKey{
  51. Key: o.APIKey,
  52. Transport: http.DefaultTransport,
  53. },
  54. }
  55. return hc, o.Endpoint, nil
  56. }
  57. if o.ServiceAccountJSONFilename != "" {
  58. ts, err := serviceAcctTokenSource(ctx, o.ServiceAccountJSONFilename, o.Scopes...)
  59. if err != nil {
  60. return nil, "", err
  61. }
  62. o.TokenSource = ts
  63. }
  64. if o.TokenSource == nil {
  65. var err error
  66. o.TokenSource, err = google.DefaultTokenSource(ctx, o.Scopes...)
  67. if err != nil {
  68. return nil, "", fmt.Errorf("google.DefaultTokenSource: %v", err)
  69. }
  70. }
  71. return oauth2.NewClient(ctx, o.TokenSource), o.Endpoint, nil
  72. }
  73. // Set at init time by dial_appengine.go. If nil, we're not on App Engine.
  74. var appengineDialerHook func(context.Context) grpc.DialOption
  75. // DialGRPC returns a GRPC connection for use communicating with a Google cloud
  76. // service, configured with the given ClientOptions.
  77. func DialGRPC(ctx context.Context, opts ...option.ClientOption) (*grpc.ClientConn, error) {
  78. var o internal.DialSettings
  79. for _, opt := range opts {
  80. opt.Apply(&o)
  81. }
  82. if o.HTTPClient != nil {
  83. return nil, errors.New("unsupported HTTP client specified")
  84. }
  85. if o.GRPCConn != nil {
  86. return o.GRPCConn, nil
  87. }
  88. if o.ServiceAccountJSONFilename != "" {
  89. ts, err := serviceAcctTokenSource(ctx, o.ServiceAccountJSONFilename, o.Scopes...)
  90. if err != nil {
  91. return nil, err
  92. }
  93. o.TokenSource = ts
  94. }
  95. if o.TokenSource == nil {
  96. var err error
  97. o.TokenSource, err = google.DefaultTokenSource(ctx, o.Scopes...)
  98. if err != nil {
  99. return nil, fmt.Errorf("google.DefaultTokenSource: %v", err)
  100. }
  101. }
  102. grpcOpts := []grpc.DialOption{
  103. grpc.WithPerRPCCredentials(oauth.TokenSource{o.TokenSource}),
  104. grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")),
  105. }
  106. if appengineDialerHook != nil {
  107. // Use the Socket API on App Engine.
  108. grpcOpts = append(grpcOpts, appengineDialerHook(ctx))
  109. }
  110. grpcOpts = append(grpcOpts, o.GRPCDialOpts...)
  111. if o.UserAgent != "" {
  112. grpcOpts = append(grpcOpts, grpc.WithUserAgent(o.UserAgent))
  113. }
  114. return grpc.DialContext(ctx, o.Endpoint, grpcOpts...)
  115. }
  116. func serviceAcctTokenSource(ctx context.Context, filename string, scope ...string) (oauth2.TokenSource, error) {
  117. data, err := ioutil.ReadFile(filename)
  118. if err != nil {
  119. return nil, fmt.Errorf("cannot read service account file: %v", err)
  120. }
  121. cfg, err := google.JWTConfigFromJSON(data, scope...)
  122. if err != nil {
  123. return nil, fmt.Errorf("google.JWTConfigFromJSON: %v", err)
  124. }
  125. return cfg.TokenSource(ctx), nil
  126. }