Debian Codegraph @

internal/website/content/tutorials/cli-uploader.md

raw
1 ---
2 title: "Tutorial: Command-Line Uploader"
3 linkTitle: "Command-Line Uploader"
4 date: 2019-03-19T18:45:53-07:00
5 weight: 1
6 ---
7
8 This quickstart will build a command line application called `upload` that
9 uploads files to blob storage on GCP, AWS, and Azure. Blob storage stores binary
10 data under a string key, and is one of the most frequently used cloud
11 services.
12
13 <!--more-->
14
15 When we're done, our command line application will work like this:
16
17 ```shell
18 # uploads gopher.png to GCS
19 $ ./upload gs://go-cloud-bucket gopher.png
20
21 # uploads gopher.png to S3
22 $ ./upload s3://go-cloud-bucket gopher.png
23
24 # uploads gopher.png to Azure
25 $ ./upload azblob://go-cloud-bucket gopher.png
26 ```
27
28 (You can download the finished tutorial [from GitHub][samples/tutorial]).
29
30 [samples/tutorial]: https://github.com/google/go-cloud/tree/master/samples/tutorial/
31
32 ## Setup
33
34 We start with a skeleton for our program to read from command-line
35 arguments to configure the bucket URL.
36
37 ```go
38 // Command upload saves files to blob storage on GCP, AWS, and Azure.
39 package main
40
41 import (
42 "log"
43 "os"
44 )
45
46 func main() {
47 // Define our input.
48 if len(os.Args) != 3 {
49 log.Fatal("usage: upload BUCKET_URL FILE")
50 }
51 bucketURL := os.Args[1]
52 file := os.Args[2]
53 _, _ = bucketURL, file
54 }
55 ```
56
57 Now that we have a basic skeleton in place, let's start filling in the pieces.
58
59 ## Connecting to the bucket
60
61 The easiest way to open a portable bucket API is with `blob.OpenBucket`.
62
63 ```go
64 package main
65
66 import (
67 // previous imports omitted
68
69 "gocloud.dev/blob"
70 )
71
72 func main() {
73 // previous code omitted
74
75 // Open a connection to the bucket.
76 b, err := blob.OpenBucket(context.Background(), bucketURL)
77 if err != nil {
78 log.Fatalf("Failed to setup bucket: %s", err)
79 }
80 defer b.Close()
81 }
82 ```
83
84 This is all we need in the `main` function to connect to the bucket. However,
85 as written, this function call will always fail: the Go CDK does not link in any
86 cloud-specific implementations of `blob.OpenBucket` unless you specifically
87 depend on them. This ensures you're only depending on the code you need.
88 To link in implementations, use blank imports:
89
90 ```go
91 package main
92
93 import (
94 // previous imports omitted
95
96 // Import the blob packages we want to be able to open.
97 _ "gocloud.dev/blob/azureblob"
98 _ "gocloud.dev/blob/gcsblob"
99 _ "gocloud.dev/blob/s3blob"
100 )
101
102 func main() {
103 // ...
104 }
105 ```
106
107 With the setup done, we're ready to use the bucket connection. Note, as a design
108 principle of the Go CDK, `blob.Bucket` does not support creating a bucket and
109 instead focuses solely on interacting with it. This separates the concerns of
110 provisioning infrastructure and using infrastructure.
111
112 ## Reading the file
113
114 We need to read our file into a slice of bytes before uploading it. The process
115 is the usual one:
116
117 ```go
118 package main
119
120 import (
121 // previous imports omitted
122 "os"
123 "io/ioutil"
124 )
125
126 func main() {
127 // ... previous code omitted
128
129 // Prepare the file for upload.
130 data, err := os.ReadFile(file)
131 if err != nil {
132 log.Fatalf("Failed to read file: %s", err)
133 }
134 }
135 ```
136
137 ## Writing the file to the bucket
138
139 Now, we have `data`, our file in a slice of bytes. Let's get to the fun part and
140 write those bytes to the bucket!
141
142 ```go
143 package main
144
145 // No new imports.
146
147 func main() {
148 // ...
149
150 w, err := b.NewWriter(ctx, file, nil)
151 if err != nil {
152 log.Fatalf("Failed to obtain writer: %s", err)
153 }
154 _, err = w.Write(data)
155 if err != nil {
156 log.Fatalf("Failed to write to bucket: %s", err)
157 }
158 if err := w.Close(); err != nil {
159 log.Fatalf("Failed to close: %s", err)
160 }
161 }
162 ```
163
164 First, we create a writer based on the bucket connection. In addition to a
165 `context.Context` type, the method takes the key under which the data will be
166 stored and the mime type of the data.
167
168 The call to `NewWriter` creates a `blob.Writer`, which implements `io.Writer`.
169 With the writer, we call `Write` passing in the data. In response, we get the
170 number of bytes written and any error that might have occurred.
171
172 Finally, we close the writer with `Close` and check the error.
173
174 Alternatively, we could have used the shortcut `b.WriteAll(ctx, file, data,
175 nil)`.
176
177 ## Uploading an image
178
179 That's it! Let's try it out. As setup, we will need to create a
180 [GCS bucket][gcs-bucket], an [S3 bucket][s3-bucket], and an
181 [Azure container][azure-container]. In the code above, I called that bucket
182 `go-cloud-bucket`, but you can change that to match whatever your bucket is
183 called. Of course, you are free to try the code on any subset of Cloud
184 providers.
185
186 * For GCP, you will need to login with
187 [gcloud](https://cloud.google.com/sdk/install). If you do not want to
188 install `gcloud`, see
189 [here](https://cloud.google.com/docs/authentication/production) for
190 alternatives.
191 * For AWS, you will need an access key ID and a secret access key. See
192 [here](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html#Using_CreateAccessKey)
193 for details. You then need to set the `AWS_REGION` environment variable to
194 the region your bucket is in.
195 * For Azure, you will need to add your storage account name and key as
196 environment variables (`AZURE_STORAGE_ACCOUNT` and
197 `AZURE_STORAGE_KEY`, respectively). See
198 [here](https://docs.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-portal)
199 for details.
200
201 With our buckets created and our credentials set up, we'll build the program
202 first:
203
204 ```shell
205 $ go build -o upload
206 ```
207
208 Then, we will send `gopher.png` (in the same directory as this README) to GCS:
209
210 ```shell
211 $ ./upload gs://go-cloud-bucket gopher.png
212 ```
213
214 Then, we send that same gopher to S3:
215
216 ```shell
217 $ ./upload s3://go-cloud-bucket?region=us-west-1 gopher.png
218 ```
219
220 Finally, we send that same gopher to Azure:
221
222 ```shell
223 $ ./upload azblob://go-cloud-bucket gopher.png
224 ```
225
226 If we check the buckets, we should see our gopher in each of them! We're done!
227
228 [s3-bucket]: https://docs.aws.amazon.com/AmazonS3/latest/gsg/CreatingABucket.html
229 [gcs-bucket]: https://cloud.google.com/storage/docs/creating-buckets
230 [azure-container]: https://docs.microsoft.com/en-us/azure/storage/blobs/storage-blobs-introduction
231
232 ## Wrapping Up
233
234 In conclusion, we have a program that can seamlessly switch between multiple
235 Cloud storage providers using just one code path. You can see the finished
236 tutorial [on GitHub][samples/tutorial].
237
238 We hope this example demonstrates how having one type for multiple clouds is a
239 huge win for simplicity and maintainability. By writing an application using a
240 generic interface like `*blob.Bucket`, we retain the option of using
241 infrastructure in whichever cloud that best fits our needs all without having to
242 worry about a rewrite. If you want to learn more, you can read about
243 [Structuring Portable Code][].
244
245 If you want to see how to deploy a Go CDK application, see [other tutorials][].
246 If you want to see how to use Go CDK APIs in your application, see the
247 [how-to guides][].
248
249 [how-to guides]: {{< ref "/howto/_index.md" >}}
250 [other tutorials]: {{< ref "/tutorials/_index.md" >}}
251 [Structuring Portable Code]: {{< ref "/concepts/structure/index.md" >}}