1 // Copyright 2014 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 15 /* 16 Package cloud is the root of the packages used to access Google Cloud 17 Services. See https://pkg.go.dev/cloud.google.com/go for a full list 18 of sub-modules. 19 20 # Client Options 21 22 All clients in sub-packages are configurable via client options. These options 23 are described here: https://pkg.go.dev/google.golang.org/api/option. 24 25 # Endpoint Override 26 27 Endpoint configuration is used to specify the URL to which requests are 28 sent. It is used for services that support or require regional endpoints, as 29 well as for other use cases such as [testing against fake servers]. 30 31 For example, the Vertex AI service recommends that you configure the endpoint to 32 the location with the features you want that is closest to your physical 33 location or the location of your users. There is no global endpoint for Vertex 34 AI. See [Vertex AI - Locations] for more details. The following example 35 demonstrates configuring a Vertex AI client with a regional endpoint: 36 37 ctx := context.Background() 38 endpoint := "us-central1-aiplatform.googleapis.com:443" 39 client, err := aiplatform.NewDatasetClient(ctx, option.WithEndpoint(endpoint)) 40 41 # Authentication and Authorization 42 43 All of the clients support authentication via [Google Application Default Credentials], 44 or by providing a JSON key file for a Service Account. See examples below. 45 46 Google Application Default Credentials (ADC) is the recommended way to authorize 47 and authenticate clients. For information on how to create and obtain 48 Application Default Credentials, see 49 https://cloud.google.com/docs/authentication/production. If you have your 50 environment configured correctly you will not need to pass any extra information 51 to the client libraries. Here is an example of a client using ADC to 52 authenticate: 53 54 client, err := secretmanager.NewClient(context.Background()) 55 if err != nil { 56 // TODO: handle error. 57 } 58 _ = client // Use the client. 59 60 You can use a file with credentials to authenticate and authorize, such as a 61 JSON key file associated with a Google service account. Service Account keys can 62 be created and downloaded from https://console.cloud.google.com/iam-admin/serviceaccounts. 63 This example uses the Secret Manger client, but the same steps apply to the 64 all other client libraries this package as well. Example: 65 66 client, err := secretmanager.NewClient(context.Background(), 67 option.WithCredentialsFile("/path/to/service-account-key.json")) 68 if err != nil { 69 // TODO: handle error. 70 } 71 _ = client // Use the client. 72 73 In some cases (for instance, you don't want to store secrets on disk), you can 74 create credentials from in-memory JSON and use the WithCredentials option. 75 This example uses the Secret Manager client, but the same steps apply to 76 all other client libraries as well. Note that scopes can be 77 found at https://developers.google.com/identity/protocols/oauth2/scopes, and 78 are also provided in all auto-generated libraries: for example, 79 cloud.google.com/go/secretmanager/apiv1 provides DefaultAuthScopes. Example: 80 81 ctx := context.Background() 82 // https://pkg.go.dev/golang.org/x/oauth2/google 83 creds, err := google.CredentialsFromJSON(ctx, []byte("JSON creds"), secretmanager.DefaultAuthScopes()...) 84 if err != nil { 85 // TODO: handle error. 86 } 87 client, err := secretmanager.NewClient(ctx, option.WithCredentials(creds)) 88 if err != nil { 89 // TODO: handle error. 90 } 91 _ = client // Use the client. 92 93 # Timeouts and Cancellation 94 95 By default, non-streaming methods, like Create or Get, will have a default 96 deadline applied to the context provided at call time, unless a context deadline 97 is already set. Streaming methods have no default deadline and will run 98 indefinitely. To set timeouts or arrange for cancellation, use 99 [context]. Transient errors will be retried when correctness allows. 100 101 Here is an example of setting a timeout for an RPC using 102 [context.WithTimeout]: 103 104 ctx := context.Background() 105 // Do not set a timeout on the context passed to NewClient: dialing happens 106 // asynchronously, and the context is used to refresh credentials in the 107 // background. 108 client, err := secretmanager.NewClient(ctx) 109 if err != nil { 110 // TODO: handle error. 111 } 112 // Time out if it takes more than 10 seconds to create a dataset. 113 tctx, cancel := context.WithTimeout(ctx, 10*time.Second) 114 defer cancel() // Always call cancel. 115 116 req := &secretmanagerpb.DeleteSecretRequest{Name: "projects/project-id/secrets/name"} 117 if err := client.DeleteSecret(tctx, req); err != nil { 118 // TODO: handle error. 119 } 120 121 Here is an example of setting a timeout for an RPC using 122 [github.com/googleapis/gax-go/v2.WithTimeout]: 123 124 ctx := context.Background() 125 // Do not set a timeout on the context passed to NewClient: dialing happens 126 // asynchronously, and the context is used to refresh credentials in the 127 // background. 128 client, err := secretmanager.NewClient(ctx) 129 if err != nil { 130 // TODO: handle error. 131 } 132 133 req := &secretmanagerpb.DeleteSecretRequest{Name: "projects/project-id/secrets/name"} 134 // Time out if it takes more than 10 seconds to create a dataset. 135 if err := client.DeleteSecret(tctx, req, gax.WithTimeout(10*time.Second)); err != nil { 136 // TODO: handle error. 137 } 138 139 Here is an example of how to arrange for an RPC to be canceled, use 140 [context.WithCancel]: 141 142 ctx := context.Background() 143 // Do not cancel the context passed to NewClient: dialing happens asynchronously, 144 // and the context is used to refresh credentials in the background. 145 client, err := secretmanager.NewClient(ctx) 146 if err != nil { 147 // TODO: handle error. 148 } 149 cctx, cancel := context.WithCancel(ctx) 150 defer cancel() // Always call cancel. 151 152 // TODO: Make the cancel function available to whatever might want to cancel the 153 // call--perhaps a GUI button. 154 req := &secretmanagerpb.DeleteSecretRequest{Name: "projects/proj/secrets/name"} 155 if err := client.DeleteSecret(cctx, req); err != nil { 156 // TODO: handle error. 157 } 158 159 Do not attempt to control the initial connection (dialing) of a service by 160 setting a timeout on the context passed to NewClient. Dialing is non-blocking, 161 so timeouts would be ineffective and would only interfere with credential 162 refreshing, which uses the same context. 163 164 # Headers 165 166 Regardless of which transport is used, request headers can be set in the same 167 way using [`callctx.SetHeaders`][setheaders]. 168 169 Here is a generic example: 170 171 // Set the header "key" to "value". 172 ctx := callctx.SetHeaders(context.Background(), "key", "value") 173 174 // Then use ctx in a subsequent request. 175 response, err := client.GetSecret(ctx, request) 176 177 ## Google-reserved headers 178 179 There are a some header keys that Google reserves for internal use that must 180 not be ovewritten. The following header keys are broadly considered reserved 181 and should not be conveyed by client library users unless instructed to do so: 182 183 * `x-goog-api-client` 184 * `x-goog-request-params` 185 186 Be sure to check the individual package documentation for other service-specific 187 reserved headers. For example, Storage supports a specific auditing header that 188 is mentioned in that [module's documentation][storagedocs]. 189 190 ## Google Cloud system parameters 191 192 Google Cloud services respect [system parameters][system parameters] that can be 193 used to augment request and/or response behavior. For the most part, they are 194 not needed when using one of the enclosed client libraries. However, those that 195 may be necessary are made available via the [`callctx`][callctx] package. If not 196 present there, consider opening an issue on that repo to request a new constant. 197 198 # Connection Pooling 199 200 Connection pooling differs in clients based on their transport. Cloud 201 clients either rely on HTTP or gRPC transports to communicate 202 with Google Cloud. 203 204 Cloud clients that use HTTP rely on the underlying HTTP transport to cache 205 connections for later re-use. These are cached to the http.MaxIdleConns 206 and http.MaxIdleConnsPerHost settings in http.DefaultTransport by default. 207 208 For gRPC clients, connection pooling is configurable. Users of Cloud Client 209 Libraries may specify option.WithGRPCConnectionPool(n) as a client option to 210 NewClient calls. This configures the underlying gRPC connections to be pooled 211 and accessed in a round robin fashion. 212 213 # Using the Libraries in Container environments(Docker) 214 215 Minimal container images like Alpine lack CA certificates. This causes RPCs to 216 appear to hang, because gRPC retries indefinitely. See 217 https://github.com/googleapis/google-cloud-go/issues/928 for more information. 218 219 # Debugging 220 221 For tips on how to write tests against code that calls into our libraries check 222 out our [Debugging Guide]. 223 224 # Testing 225 226 For tips on how to write tests against code that calls into our libraries check 227 out our [Testing Guide]. 228 229 # Inspecting errors 230 231 Most of the errors returned by the generated clients are wrapped in an 232 [github.com/googleapis/gax-go/v2/apierror.APIError] and can be further unwrapped 233 into a [google.golang.org/grpc/status.Status] or 234 [google.golang.org/api/googleapi.Error] depending on the transport used to make 235 the call (gRPC or REST). Converting your errors to these types can be a useful 236 way to get more information about what went wrong while debugging. 237 238 APIError gives access to specific details in the error. The transport-specific 239 errors can still be unwrapped using the APIError. 240 241 if err != nil { 242 var ae *apierror.APIError 243 if errors.As(err, &ae) { 244 log.Println(ae.Reason()) 245 log.Println(ae.Details().Help.GetLinks()) 246 } 247 } 248 249 If the gRPC transport was used, the [google.golang.org/grpc/status.Status] can 250 still be parsed using the [google.golang.org/grpc/status.FromError] function. 251 252 if err != nil { 253 if s, ok := status.FromError(err); ok { 254 log.Println(s.Message()) 255 for _, d := range s.Proto().Details { 256 log.Println(d) 257 } 258 } 259 } 260 261 # Client Stability 262 263 Semver is used to communicate stability of the sub-modules of this package. 264 Note, some stable sub-modules do contain packages, and sometimes features, that 265 are considered unstable. If something is unstable it will be explicitly labeled 266 as such. Example of package does in an unstable package: 267 268 NOTE: This package is in beta. It is not stable, and may be subject to changes. 269 270 Clients that contain alpha and beta in their import path may change or go away 271 without notice. 272 273 Clients marked stable will maintain compatibility with future versions for as 274 long as we can reasonably sustain. Incompatible changes might be made in some 275 situations, including: 276 277 - Security bugs may prompt backwards-incompatible changes. 278 - Situations in which components are no longer feasible to maintain without 279 making breaking changes, including removal. 280 - Parts of the client surface may be outright unstable and subject to change. 281 These parts of the surface will be labeled with the note, "It is EXPERIMENTAL 282 and subject to change or removal without notice." 283 284 [testing against fake servers]: https://github.com/googleapis/google-cloud-go/blob/main/testing.md#testing-grpc-services-using-fakes 285 [Vertex AI - Locations]: https://cloud.google.com/vertex-ai/docs/general/locations 286 [Google Application Default Credentials]: https://cloud.google.com/docs/authentication/external/set-up-adc 287 [Testing Guide]: https://github.com/googleapis/google-cloud-go/blob/main/testing.md 288 [Debugging Guide]: https://github.com/googleapis/google-cloud-go/blob/main/debug.md 289 [callctx]: https://pkg.go.dev/github.com/googleapis/gax-go/v2/callctx#pkg-constants 290 [setheaders]: https://pkg.go.dev/github.com/googleapis/gax-go/v2/callctx#SetHeaders 291 [storagedocs]: https://pkg.go.dev/cloud.google.com/go/storage#hdr-Sending_Custom_Headers 292 [system parameters]: https://cloud.google.com/apis/docs/system-parameters 293 */ 294 package cloud // import "cloud.google.com/go" 295