File: zt_examples_test.go

package info (click to toggle)
golang-github-azure-azure-storage-blob-go 0.15.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 2,084 kB
  • sloc: makefile: 3
file content (1435 lines) | stat: -rw-r--r-- 63,628 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
package azblob

import (
	"bytes"
	"context"
	"encoding/base64"
	"encoding/binary"
	"fmt"
	"io"
	"log"
	"math/rand"
	"net"
	"net/http"
	"net/url"
	"os"
	"reflect"
	"strings"
	"time"

	"github.com/Azure/go-autorest/autorest/adal"

	"github.com/Azure/azure-pipeline-go/pipeline"
)

// https://godoc.org/github.com/fluhus/godoc-tricks

func accountInfo() (string, string) {
	return os.Getenv("ACCOUNT_NAME"), os.Getenv("ACCOUNT_KEY")
}

// This example shows how to get started using the Azure Storage Blob SDK for Go.
func Example() {
	// From the Azure portal, get your Storage account's name and account key.
	accountName, accountKey := accountInfo()

	// Use your Storage account's name and key to create a credential object; this is used to access your account.
	credential, err := NewSharedKeyCredential(accountName, accountKey)
	if err != nil {
		log.Fatal(err)
	}

	// Create a request pipeline that is used to process HTTP(S) requests and responses. It requires
	// your account credentials. In more advanced scenarios, you can configure telemetry, retry policies,
	// logging, and other options. Also, you can configure multiple request pipelines for different scenarios.
	p := NewPipeline(credential, PipelineOptions{})

	// From the Azure portal, get your Storage account blob service URL endpoint.
	// The URL typically looks like this:
	u, _ := url.Parse(fmt.Sprintf("https://%s.blob.core.windows.net", accountName))

	// Create an ServiceURL object that wraps the service URL and a request pipeline.
	serviceURL := NewServiceURL(*u, p)

	// Now, you can use the serviceURL to perform various container and blob operations.

	// All HTTP operations allow you to specify a Go context.Context object to control cancellation/timeout.
	ctx := context.Background() // This example uses a never-expiring context.

	// This example shows several common operations just to get you started.

	// Create a URL that references a to-be-created container in your Azure Storage account.
	// This returns a ContainerURL object that wraps the container's URL and a request pipeline (inherited from serviceURL)
	containerURL := serviceURL.NewContainerURL("mycontainer") // Container names require lowercase

	// Create the container on the service (with no metadata and no public access)
	_, err = containerURL.Create(ctx, Metadata{}, PublicAccessNone)
	if err != nil {
		log.Fatal(err)
	}

	// Create a URL that references a to-be-created blob in your Azure Storage account's container.
	// This returns a BlockBlobURL object that wraps the blob's URL and a request pipeline (inherited from containerURL)
	blobURL := containerURL.NewBlockBlobURL("HelloWorld.txt") // Blob names can be mixed case

	// Create the blob with string (plain text) content.
	data := "Hello World!"
	_, err = blobURL.Upload(ctx, strings.NewReader(data), BlobHTTPHeaders{ContentType: "text/plain"}, Metadata{}, BlobAccessConditions{}, DefaultAccessTier, nil, ClientProvidedKeyOptions{}, ImmutabilityPolicyOptions{})
	if err != nil {
		log.Fatal(err)
	}

	// Download the blob's contents and verify that it worked correctly
	get, err := blobURL.Download(ctx, 0, 0, BlobAccessConditions{}, false, ClientProvidedKeyOptions{})
	if err != nil {
		log.Fatal(err)
	}

	downloadedData := &bytes.Buffer{}
	reader := get.Body(RetryReaderOptions{})
	downloadedData.ReadFrom(reader)
	reader.Close() // The client must close the response body when finished with it
	if data != downloadedData.String() {
		log.Fatal("downloaded data doesn't match uploaded data")
	}

	// List the blob(s) in our container; since a container may hold millions of blobs, this is done 1 segment at a time.
	for marker := (Marker{}); marker.NotDone(); { // The parens around Marker{} are required to avoid compiler error.
		// Get a result segment starting with the blob indicated by the current Marker.
		listBlob, err := containerURL.ListBlobsFlatSegment(ctx, marker, ListBlobsSegmentOptions{})
		if err != nil {
			log.Fatal(err)
		}
		// IMPORTANT: ListBlobs returns the start of the next segment; you MUST use this to get
		// the next segment (after processing the current result segment).
		marker = listBlob.NextMarker

		// Process the blobs returned in this result segment (if the segment is empty, the loop body won't execute)
		for _, blobInfo := range listBlob.Segment.BlobItems {
			fmt.Print("Blob name: " + blobInfo.Name + "\n")
		}
	}

	// Delete the blob we created earlier.
	_, err = blobURL.Delete(ctx, DeleteSnapshotsOptionNone, BlobAccessConditions{})
	if err != nil {
		log.Fatal(err)
	}

	// Delete the container we created earlier.
	_, err = containerURL.Delete(ctx, ContainerAccessConditions{})
	if err != nil {
		log.Fatal(err)
	}
}

// This example shows how you can configure a pipeline for making HTTP requests to the Azure Storage Blob Service.
func ExampleNewPipeline() {
	// This example shows how to wire in your own logging mechanism (this example uses
	// Go's standard logger to write log information to standard error)
	logger := log.New(os.Stderr, "", log.Ldate|log.Lmicroseconds)

	// Create/configure a request pipeline options object.
	// All PipelineOptions' fields are optional; reasonable defaults are set for anything you do not specify
	po := PipelineOptions{
		// Set RetryOptions to control how HTTP request are retried when retryable failures occur
		Retry: RetryOptions{
			Policy:        RetryPolicyExponential, // Use exponential backoff as opposed to linear
			MaxTries:      3,                      // Try at most 3 times to perform the operation (set to 1 to disable retries)
			TryTimeout:    time.Second * 3,        // Maximum time allowed for any single try
			RetryDelay:    time.Second * 1,        // Backoff amount for each retry (exponential or linear)
			MaxRetryDelay: time.Second * 3,        // Max delay between retries
		},

		// Set RequestLogOptions to control how each HTTP request & its response is logged
		RequestLog: RequestLogOptions{
			LogWarningIfTryOverThreshold: time.Millisecond * 200, // A successful response taking more than this time to arrive is logged as a warning
			SyslogDisabled:               true,
		},

		// Set LogOptions to control what & where all pipeline log events go
		Log: pipeline.LogOptions{
			Log: func(s pipeline.LogLevel, m string) { // This func is called to log each event
				// This method is not called for filtered-out severities.
				logger.Output(2, m) // This example uses Go's standard logger
			},
			ShouldLog: func(level pipeline.LogLevel) bool {
				return level <= pipeline.LogWarning // Log all events from warning to more severe
			},
		},

		// Set HTTPSender to override the default HTTP Sender that sends the request over the network
		HTTPSender: pipeline.FactoryFunc(func(next pipeline.Policy, po *pipeline.PolicyOptions) pipeline.PolicyFunc {
			return func(ctx context.Context, request pipeline.Request) (pipeline.Response, error) {
				// Implement the HTTP client that will override the default sender.
				// For example, below HTTP client uses a transport that is different from http.DefaultTransport
				client := http.Client{
					Transport: &http.Transport{
						Proxy: nil,
						DialContext: (&net.Dialer{
							Timeout:   30 * time.Second,
							KeepAlive: 30 * time.Second,
							DualStack: true,
						}).DialContext,
						MaxIdleConns:          100,
						IdleConnTimeout:       180 * time.Second,
						TLSHandshakeTimeout:   10 * time.Second,
						ExpectContinueTimeout: 1 * time.Second,
					},
				}

				// Send the request over the network
				resp, err := client.Do(request.WithContext(ctx))

				return pipeline.NewHTTPResponse(resp), err
			}
		}),
	}

	// Create a request pipeline object configured with credentials and with pipeline options. Once created,
	// a pipeline object is goroutine-safe and can be safely used with many XxxURL objects simultaneously.
	p := NewPipeline(NewAnonymousCredential(), po) // A pipeline always requires some credential object

	// Once you've created a pipeline object, associate it with an XxxURL object so that you can perform HTTP requests with it.
	u, _ := url.Parse("https://myaccount.blob.core.windows.net")
	serviceURL := NewServiceURL(*u, p)
	// Use the serviceURL as desired...

	// NOTE: When you use an XxxURL object to create another XxxURL object, the new XxxURL object inherits the
	// same pipeline object as its parent. For example, the containerURL and blobURL objects (created below)
	// all share the same pipeline. Any HTTP operations you perform with these objects share the behavior (retry, logging, etc.)
	containerURL := serviceURL.NewContainerURL("mycontainer")
	blobURL := containerURL.NewBlockBlobURL("ReadMe.txt")

	// If you'd like to perform some operations with different behavior, create a new pipeline object and
	// associate it with a new XxxURL object by passing the new pipeline to the XxxURL object's WithPipeline method.

	// In this example, I reconfigure the retry policies, create a new pipeline, and then create a new
	// ContainerURL object that has the same URL as its parent.
	po.Retry = RetryOptions{
		Policy:        RetryPolicyFixed, // Use fixed time backoff
		MaxTries:      4,                // Try at most 3 times to perform the operation (set to 1 to disable retries)
		TryTimeout:    time.Minute * 1,  // Maximum time allowed for any single try
		RetryDelay:    time.Second * 5,  // Backoff amount for each retry (exponential or linear)
		MaxRetryDelay: time.Second * 10, // Max delay between retries
	}
	newContainerURL := containerURL.WithPipeline(NewPipeline(NewAnonymousCredential(), po))

	// Now, any XxxBlobURL object created using newContainerURL inherits the pipeline with the new retry policy.
	newBlobURL := newContainerURL.NewBlockBlobURL("ReadMe.txt")
	_, _ = blobURL, newBlobURL // Avoid compiler's "declared and not used" error
}

func ExampleStorageError() {
	// This example shows how to handle errors returned from various XxxURL methods. All these methods return an
	// object implementing the pipeline.Response interface and an object implementing Go's error interface.
	// The error result is nil if the request was successful; your code can safely use the Response interface object.
	// If error is non-nil, the error could be due to:

	// 1. An invalid argument passed to the method. You should not write code to handle these errors;
	//    instead, fix these errors as they appear during development/testing.

	// 2. A network request didn't reach an Azure Storage Service. This usually happens due to a bad URL or
	//    faulty networking infrastructure (like a router issue). In this case, an object implementing the
	//    net.Error interface will be returned. The net.Error interface offers Timeout and Temporary methods
	//    which return true if the network error is determined to be a timeout or temporary condition. If
	//    your pipeline uses the retry policy factory, then this policy looks for Timeout/Temporary and
	//    automatically retries based on the retry options you've configured. Because of the retry policy,
	//    your code will usually not call the Timeout/Temporary methods explicitly other than possibly logging
	//    the network failure.

	// 3. A network request did reach the Azure Storage Service but the service failed to perform the
	//    requested operation. In this case, an object implementing the StorageError interface is returned.
	//    The StorageError interface also implements the net.Error interface and, if you use the retry policy,
	//    you would most likely ignore the Timeout/Temporary methods. However, the StorageError interface exposes
	//    richer information such as a service error code, an error description, details data, and the
	//    service-returned http.Response. And, from the http.Response, you can get the initiating http.Request.

	u, _ := url.Parse("http://myaccount.blob.core.windows.net/mycontainer")
	containerURL := NewContainerURL(*u, NewPipeline(NewAnonymousCredential(), PipelineOptions{}))
	create, err := containerURL.Create(context.Background(), Metadata{}, PublicAccessNone)

	if err != nil { // An error occurred
		if stgErr, ok := err.(StorageError); ok { // This error is a Service-specific error
			// StorageError also implements net.Error so you could call its Timeout/Temporary methods if you want.
			switch stgErr.ServiceCode() { // Compare serviceCode to various ServiceCodeXxx constants
			case ServiceCodeContainerAlreadyExists:
				// You can also look at the http.Response object that failed.
				if failedResponse := stgErr.Response(); failedResponse != nil {
					// From the response object, you can get the initiating http.Request object
					failedRequest := failedResponse.Request
					_ = failedRequest // Avoid compiler's "declared and not used" error
				}

			case ServiceCodeContainerBeingDeleted:
				// Handle this error ...
			default:
				// Handle other errors ...
			}
		}
		log.Fatal(err) // Error is not due to Azure Storage service; networking infrastructure failure
	}

	// If err is nil, then the method was successful; use the response to access the result
	_ = create // Avoid compiler's "declared and not used" error
}

// This example shows how to break a URL into its parts so you can
// examine and/or change some of its values and then construct a new URL.
func ExampleBlobURLParts() {
	// Let's start with a URL that identifies a snapshot of a blob in a container.
	// The URL also contains a Shared Access Signature (SAS):
	u, _ := url.Parse("https://myaccount.blob.core.windows.net/mycontainter/ReadMe.txt?" +
		"snapshot=2011-03-09T01:42:34Z&" +
		"sv=2015-02-21&sr=b&st=2111-01-09T01:42:34.936Z&se=2222-03-09T01:42:34.936Z&sp=rw&sip=168.1.5.60-168.1.5.70&" +
		"spr=https,http&si=myIdentifier&ss=bf&srt=s&sig=92836758923659283652983562==")

	// You can parse this URL into its constituent parts:
	parts := NewBlobURLParts(*u)

	// Now, we access the parts (this example prints them).
	fmt.Println(parts.Host, parts.ContainerName, parts.BlobName, parts.Snapshot)
	sas := parts.SAS
	fmt.Println(sas.Version(), sas.Resource(), sas.StartTime(), sas.ExpiryTime(), sas.Permissions(),
		sas.IPRange(), sas.Protocol(), sas.Identifier(), sas.Services(), sas.Signature())

	// You can then change some of the fields and construct a new URL:
	parts.SAS = SASQueryParameters{}       // Remove the SAS query parameters
	parts.Snapshot = ""                    // Remove the snapshot timestamp
	parts.ContainerName = "othercontainer" // Change the container name
	// In this example, we'll keep the blob name as is.

	// Construct a new URL from the parts:
	newURL := parts.URL()
	fmt.Print(newURL.String())
	// NOTE: You can pass the new URL to NewBlockBlobURL (or similar methods) to manipulate the blob.
}

// This example shows how to create and use an Azure Storage account Shared Access Signature (SAS).
func ExampleAccountSASSignatureValues() {
	// From the Azure portal, get your Storage account's name and account key.
	accountName, accountKey := accountInfo()

	// Use your Storage account's name and key to create a credential object; this is required to sign a SAS.
	credential, err := NewSharedKeyCredential(accountName, accountKey)
	if err != nil {
		log.Fatal(err)
	}

	// Set the desired SAS signature values and sign them with the shared key credentials to get the SAS query parameters.
	sasQueryParams, err := AccountSASSignatureValues{
		Protocol:      SASProtocolHTTPS,                     // Users MUST use HTTPS (not HTTP)
		ExpiryTime:    time.Now().UTC().Add(48 * time.Hour), // 48-hours before expiration
		Permissions:   AccountSASPermissions{Read: true, List: true}.String(),
		Services:      AccountSASServices{Blob: true}.String(),
		ResourceTypes: AccountSASResourceTypes{Container: true, Object: true}.String(),
	}.NewSASQueryParameters(credential)
	if err != nil {
		log.Fatal(err)
	}

	qp := sasQueryParams.Encode()
	urlToSendToSomeone := fmt.Sprintf("https://%s.blob.core.windows.net?%s", accountName, qp)
	// At this point, you can send the urlToSendToSomeone to someone via email or any other mechanism you choose.

	// ************************************************************************************************

	// When someone receives the URL, they access the SAS-protected resource with code like this:
	u, _ := url.Parse(urlToSendToSomeone)

	// Create an ServiceURL object that wraps the service URL (and its SAS) and a pipeline.
	// When using a SAS URLs, anonymous credentials are required.
	serviceURL := NewServiceURL(*u, NewPipeline(NewAnonymousCredential(), PipelineOptions{}))
	// Now, you can use this serviceURL just like any other to make requests of the resource.

	// You can parse a URL into its constituent parts:
	blobURLParts := NewBlobURLParts(serviceURL.URL())
	fmt.Printf("SAS expiry time=%v", blobURLParts.SAS.ExpiryTime())

	_ = serviceURL // Avoid compiler's "declared and not used" error
}

// This example shows how to create and use a Blob Service Shared Access Signature (SAS).
func ExampleBlobSASSignatureValues() {
	// From the Azure portal, get your Storage account's name and account key.
	accountName, accountKey := accountInfo()

	// Use your Storage account's name and key to create a credential object; this is required to sign a SAS.
	credential, err := NewSharedKeyCredential(accountName, accountKey)
	if err != nil {
		log.Fatal(err)
	}

	// This is the name of the container and blob that we're creating a SAS to.
	containerName := "mycontainer" // Container names require lowercase
	blobName := "HelloWorld.txt"   // Blob names can be mixed case

	// Set the desired SAS signature values and sign them with the shared key credentials to get the SAS query parameters.
	sasQueryParams, err := BlobSASSignatureValues{
		Protocol:      SASProtocolHTTPS,                     // Users MUST use HTTPS (not HTTP)
		ExpiryTime:    time.Now().UTC().Add(48 * time.Hour), // 48-hours before expiration
		ContainerName: containerName,
		BlobName:      blobName,

		// To produce a container SAS (as opposed to a blob SAS), assign to Permissions using
		// ContainerSASPermissions and make sure the BlobName field is "" (the default).
		Permissions: BlobSASPermissions{Add: true, Read: true, Write: true}.String(),
	}.NewSASQueryParameters(credential)
	if err != nil {
		log.Fatal(err)
	}

	// Create the URL of the resource you wish to access and append the SAS query parameters.
	// Since this is a blob SAS, the URL is to the Azure storage blob.
	qp := sasQueryParams.Encode()
	urlToSendToSomeone := fmt.Sprintf("https://%s.blob.core.windows.net/%s/%s?%s",
		accountName, containerName, blobName, qp)
	// At this point, you can send the urlToSendToSomeone to someone via email or any other mechanism you choose.

	// ************************************************************************************************

	// When someone receives the URL, they access the SAS-protected resource with code like this:
	u, _ := url.Parse(urlToSendToSomeone)

	// Create an BlobURL object that wraps the blob URL (and its SAS) and a pipeline.
	// When using a SAS URLs, anonymous credentials are required.
	blobURL := NewBlobURL(*u, NewPipeline(NewAnonymousCredential(), PipelineOptions{}))
	// Now, you can use this blobURL just like any other to make requests of the resource.

	// If you have a SAS query parameter string, you can parse it into its parts:
	blobURLParts := NewBlobURLParts(blobURL.URL())
	fmt.Printf("SAS expiry time=%v", blobURLParts.SAS.ExpiryTime())

	_ = blobURL // Avoid compiler's "declared and not used" error
}

// This example shows how to manipulate a container's permissions.
func ExampleContainerURL_SetContainerAccessPolicy() {
	// From the Azure portal, get your Storage account's name and account key.
	accountName, accountKey := accountInfo()

	// Use your Storage account's name and key to create a credential object; this is used to access your account.
	credential, err := NewSharedKeyCredential(accountName, accountKey)
	if err != nil {
		log.Fatal(err)
	}

	// Create an ContainerURL object that wraps the container's URL and a default pipeline.
	u, _ := url.Parse(fmt.Sprintf("https://%s.blob.core.windows.net/mycontainer", accountName))
	containerURL := NewContainerURL(*u, NewPipeline(credential, PipelineOptions{}))

	// All operations allow you to specify a timeout via a Go context.Context object.
	ctx := context.Background() // This example uses a never-expiring context

	// Create the container (with no metadata and no public access)
	_, err = containerURL.Create(ctx, Metadata{}, PublicAccessNone)
	if err != nil {
		log.Fatal(err)
	}

	// Create a URL that references a to-be-created blob in your Azure Storage account's container.
	// This returns a BlockBlobURL object that wraps the blob's URL and a request pipeline (inherited from containerURL)
	blobURL := containerURL.NewBlockBlobURL("HelloWorld.txt") // Blob names can be mixed case

	// Create the blob and put some text in it
	_, err = blobURL.Upload(ctx, strings.NewReader("Hello World!"), BlobHTTPHeaders{ContentType: "text/plain"}, Metadata{}, BlobAccessConditions{}, DefaultAccessTier, nil, ClientProvidedKeyOptions{}, ImmutabilityPolicyOptions{})
	if err != nil {
		log.Fatal(err)
	}

	// Attempt to read the blob via a simple HTTP GET operation
	rawBlobURL := blobURL.URL()
	get, err := http.Get(rawBlobURL.String())
	if err != nil {
		log.Fatal(err)
	}
	if get.StatusCode == http.StatusNotFound {
		// We expected this error because the service returns an HTTP 404 status code when a blob
		// exists but the requester does not have permission to access it.
		// This is how we change the container's permission to allow public/anonymous aceess:
		_, err := containerURL.SetAccessPolicy(ctx, PublicAccessBlob, []SignedIdentifier{}, ContainerAccessConditions{})
		if err != nil {
			log.Fatal(err)
		}

		// Now, this works:
		get, err = http.Get(rawBlobURL.String())
		if err != nil {
			log.Fatal(err)
		}
		defer get.Body.Close()
		var text bytes.Buffer
		text.ReadFrom(get.Body)
		fmt.Print(text.String())
	}
}

// This example shows how to perform operations on blob conditionally.
func ExampleBlobAccessConditions() {
	// From the Azure portal, get your Storage account's name and account key.
	accountName, accountKey := accountInfo()

	// Create a BlockBlobURL object that wraps a blob's URL and a default pipeline.
	u, _ := url.Parse(fmt.Sprintf("https://%s.blob.core.windows.net/mycontainer/Data.txt", accountName))
	credential, err := NewSharedKeyCredential(accountName, accountKey)
	if err != nil {
		log.Fatal(err)
	}
	blobURL := NewBlockBlobURL(*u, NewPipeline(credential, PipelineOptions{}))

	ctx := context.Background() // This example uses a never-expiring context

	// This helper function displays the results of an operation; it is called frequently below.
	showResult := func(response pipeline.Response, err error) {
		if err != nil {
			if stgErr, ok := err.(StorageError); !ok {
				log.Fatal(err) // Network failure
			} else {
				fmt.Print("Failure: " + stgErr.Response().Status + "\n")
			}
		} else {
			if get, ok := response.(*DownloadResponse); ok {
				get.Body(RetryReaderOptions{}).Close() // The client must close the response body when finished with it
			}
			fmt.Print("Success: " + response.Response().Status + "\n")
		}
	}

	// Create the blob (unconditionally; succeeds)
	upload, err := blobURL.Upload(ctx, strings.NewReader("Text-1"), BlobHTTPHeaders{}, Metadata{}, BlobAccessConditions{}, DefaultAccessTier, nil, ClientProvidedKeyOptions{}, ImmutabilityPolicyOptions{})
	showResult(upload, err)

	// Download blob content if the blob has been modified since we uploaded it (fails):
	showResult(blobURL.Download(ctx, 0, 0, BlobAccessConditions{ModifiedAccessConditions: ModifiedAccessConditions{IfModifiedSince: upload.LastModified()}}, false, ClientProvidedKeyOptions{}))

	// Download blob content if the blob hasn't been modified in the last 24 hours (fails):
	showResult(blobURL.Download(ctx, 0, 0, BlobAccessConditions{ModifiedAccessConditions: ModifiedAccessConditions{IfUnmodifiedSince: time.Now().UTC().Add(time.Hour * -24)}}, false, ClientProvidedKeyOptions{}))

	// Upload new content if the blob hasn't changed since the version identified by ETag (succeeds):
	upload, err = blobURL.Upload(ctx, strings.NewReader("Text-2"), BlobHTTPHeaders{}, Metadata{}, BlobAccessConditions{ModifiedAccessConditions: ModifiedAccessConditions{IfMatch: upload.ETag()}}, DefaultAccessTier, nil, ClientProvidedKeyOptions{}, ImmutabilityPolicyOptions{})
	showResult(upload, err)

	// Download content if it has changed since the version identified by ETag (fails):
	showResult(blobURL.Download(ctx, 0, 0, BlobAccessConditions{ModifiedAccessConditions: ModifiedAccessConditions{IfNoneMatch: upload.ETag()}}, false, ClientProvidedKeyOptions{}))

	// Upload content if the blob doesn't already exist (fails):
	showResult(blobURL.Upload(ctx, strings.NewReader("Text-3"), BlobHTTPHeaders{}, Metadata{}, BlobAccessConditions{ModifiedAccessConditions: ModifiedAccessConditions{IfNoneMatch: ETagAny}}, DefaultAccessTier, nil, ClientProvidedKeyOptions{}, ImmutabilityPolicyOptions{}))
}

// This examples shows how to create a container with metadata and then how to read & update the metadata.
func ExampleMetadata_containers() {
	// From the Azure portal, get your Storage account blob service URL endpoint.
	accountName, accountKey := accountInfo()

	// Create a ContainerURL object that wraps a soon-to-be-created container's URL and a default pipeline.
	u, _ := url.Parse(fmt.Sprintf("https://%s.blob.core.windows.net/mycontainer", accountName))
	credential, err := NewSharedKeyCredential(accountName, accountKey)
	if err != nil {
		log.Fatal(err)
	}
	containerURL := NewContainerURL(*u, NewPipeline(credential, PipelineOptions{}))

	ctx := context.Background() // This example uses a never-expiring context

	// Create a container with some metadata (string key/value pairs)
	// NOTE: Metadata key names are always converted to lowercase before being sent to the Storage Service.
	// Therefore, you should always use lowercase letters; especially when querying a map for a metadata key.
	creatingApp, _ := os.Executable()
	_, err = containerURL.Create(ctx, Metadata{"author": "Jeffrey", "app": creatingApp}, PublicAccessNone)
	if err != nil {
		log.Fatal(err)
	}

	// Query the container's metadata
	get, err := containerURL.GetProperties(ctx, LeaseAccessConditions{})
	if err != nil {
		log.Fatal(err)
	}

	// Show the container's metadata
	metadata := get.NewMetadata()
	for k, v := range metadata {
		fmt.Print(k + "=" + v + "\n")
	}

	// Update the metadata and write it back to the container
	metadata["author"] = "Aidan" // NOTE: The keyname is in all lowercase letters
	_, err = containerURL.SetMetadata(ctx, metadata, ContainerAccessConditions{})
	if err != nil {
		log.Fatal(err)
	}

	// NOTE: The SetMetadata & SetProperties methods update the container's ETag & LastModified properties
}

// This examples shows how to create a blob with metadata and then how to read & update
// the blob's read-only properties and metadata.
func ExampleMetadata_blobs() {
	// From the Azure portal, get your Storage account blob service URL endpoint.
	accountName, accountKey := accountInfo()

	// Create a ContainerURL object that wraps a soon-to-be-created blob's URL and a default pipeline.
	u, _ := url.Parse(fmt.Sprintf("https://%s.blob.core.windows.net/mycontainer/ReadMe.txt", accountName))
	credential, err := NewSharedKeyCredential(accountName, accountKey)
	if err != nil {
		log.Fatal(err)
	}
	blobURL := NewBlockBlobURL(*u, NewPipeline(credential, PipelineOptions{}))

	ctx := context.Background() // This example uses a never-expiring context

	// Create a blob with metadata (string key/value pairs)
	// NOTE: Metadata key names are always converted to lowercase before being sent to the Storage Service.
	// Therefore, you should always use lowercase letters; especially when querying a map for a metadata key.
	creatingApp, _ := os.Executable()
	_, err = blobURL.Upload(ctx, strings.NewReader("Some text"), BlobHTTPHeaders{}, Metadata{"author": "Jeffrey", "app": creatingApp}, BlobAccessConditions{}, DefaultAccessTier, nil, ClientProvidedKeyOptions{}, ImmutabilityPolicyOptions{})
	if err != nil {
		log.Fatal(err)
	}

	// Query the blob's properties and metadata
	get, err := blobURL.GetProperties(ctx, BlobAccessConditions{}, ClientProvidedKeyOptions{})
	if err != nil {
		log.Fatal(err)
	}

	// Show some of the blob's read-only properties
	fmt.Println(get.BlobType(), get.ETag(), get.LastModified())

	// Show the blob's metadata
	metadata := get.NewMetadata()
	for k, v := range metadata {
		fmt.Print(k + "=" + v + "\n")
	}

	// Update the blob's metadata and write it back to the blob
	metadata["editor"] = "Grant" // Add a new key/value; NOTE: The keyname is in all lowercase letters
	_, err = blobURL.SetMetadata(ctx, metadata, BlobAccessConditions{}, ClientProvidedKeyOptions{})
	if err != nil {
		log.Fatal(err)
	}

	// NOTE: The SetMetadata method updates the blob's ETag & LastModified properties
}

// This examples shows how to create a blob with HTTP Headers and then how to read & update
// the blob's HTTP headers.
func ExampleBlobHTTPHeaders() {
	// From the Azure portal, get your Storage account blob service URL endpoint.
	accountName, accountKey := accountInfo()

	// Create a ContainerURL object that wraps a soon-to-be-created blob's URL and a default pipeline.
	u, _ := url.Parse(fmt.Sprintf("https://%s.blob.core.windows.net/mycontainer/ReadMe.txt", accountName))
	credential, err := NewSharedKeyCredential(accountName, accountKey)
	if err != nil {
		log.Fatal(err)
	}
	blobURL := NewBlockBlobURL(*u, NewPipeline(credential, PipelineOptions{}))

	ctx := context.Background() // This example uses a never-expiring context

	// Create a blob with HTTP headers
	_, err = blobURL.Upload(ctx, strings.NewReader("Some text"), BlobHTTPHeaders{
		ContentType:        "text/html; charset=utf-8",
		ContentDisposition: "attachment",
	}, Metadata{}, BlobAccessConditions{}, DefaultAccessTier, nil, ClientProvidedKeyOptions{}, ImmutabilityPolicyOptions{})
	if err != nil {
		log.Fatal(err)
	}

	// GetMetadata returns the blob's properties, HTTP headers, and metadata
	get, err := blobURL.GetProperties(ctx, BlobAccessConditions{}, ClientProvidedKeyOptions{})
	if err != nil {
		log.Fatal(err)
	}

	// Show some of the blob's read-only properties
	fmt.Println(get.BlobType(), get.ETag(), get.LastModified())

	// Shows some of the blob's HTTP Headers
	httpHeaders := get.NewHTTPHeaders()
	fmt.Println(httpHeaders.ContentType, httpHeaders.ContentDisposition)

	// Update the blob's HTTP Headers and write them back to the blob
	httpHeaders.ContentType = "text/plain"
	_, err = blobURL.SetHTTPHeaders(ctx, httpHeaders, BlobAccessConditions{})
	if err != nil {
		log.Fatal(err)
	}

	// NOTE: The SetMetadata method updates the blob's ETag & LastModified properties
}

// ExampleBlockBlobURL shows how to upload a lot of data (in blocks) to a blob.
// A block blob can have a maximum of 50,000 blocks; each block can have a maximum of 100MB.
// Therefore, the maximum size of a block blob is slightly more than 4.75 TB (100 MB X 50,000 blocks).
func ExampleBlockBlobURL() {
	// From the Azure portal, get your Storage account blob service URL endpoint.
	accountName, accountKey := accountInfo()

	// Create a ContainerURL object that wraps a soon-to-be-created blob's URL and a default pipeline.
	u, _ := url.Parse(fmt.Sprintf("https://%s.blob.core.windows.net/mycontainer/MyBlockBlob.txt", accountName))
	credential, err := NewSharedKeyCredential(accountName, accountKey)
	if err != nil {
		log.Fatal(err)
	}
	blobURL := NewBlockBlobURL(*u, NewPipeline(credential, PipelineOptions{}))

	ctx := context.Background() // This example uses a never-expiring context

	// These helper functions convert a binary block ID to a base-64 string and vice versa
	// NOTE: The blockID must be <= 64 bytes and ALL blockIDs for the block must be the same length
	blockIDBinaryToBase64 := func(blockID []byte) string { return base64.StdEncoding.EncodeToString(blockID) }
	blockIDBase64ToBinary := func(blockID string) []byte { binary, _ := base64.StdEncoding.DecodeString(blockID); return binary }

	// These helper functions convert an int block ID to a base-64 string and vice versa
	blockIDIntToBase64 := func(blockID int) string {
		binaryBlockID := (&[4]byte{})[:] // All block IDs are 4 bytes long
		binary.LittleEndian.PutUint32(binaryBlockID, uint32(blockID))
		return blockIDBinaryToBase64(binaryBlockID)
	}
	blockIDBase64ToInt := func(blockID string) int {
		blockIDBase64ToBinary(blockID)
		return int(binary.LittleEndian.Uint32(blockIDBase64ToBinary(blockID)))
	}

	// Upload 4 blocks to the blob (these blocks are tiny; they can be up to 100MB each)
	words := []string{"Azure ", "Storage ", "Block ", "Blob."}
	base64BlockIDs := make([]string, len(words)) // The collection of block IDs (base 64 strings)

	// Upload each block sequentially (one after the other); for better performance, you want to upload multiple blocks in parallel)
	for index, word := range words {
		// This example uses the index as the block ID; convert the index/ID into a base-64 encoded string as required by the service.
		// NOTE: Over the lifetime of a blob, all block IDs (before base 64 encoding) must be the same length (this example uses 4 byte block IDs).
		base64BlockIDs[index] = blockIDIntToBase64(index) // Some people use UUIDs for block IDs

		// Upload a block to this blob specifying the Block ID and its content (up to 100MB); this block is uncommitted.
		_, err := blobURL.StageBlock(ctx, base64BlockIDs[index], strings.NewReader(word), LeaseAccessConditions{}, nil, ClientProvidedKeyOptions{})
		if err != nil {
			log.Fatal(err)
		}
	}

	// After all the blocks are uploaded, atomically commit them to the blob.
	_, err = blobURL.CommitBlockList(ctx, base64BlockIDs, BlobHTTPHeaders{}, Metadata{}, BlobAccessConditions{}, DefaultAccessTier, nil, ClientProvidedKeyOptions{}, ImmutabilityPolicyOptions{})
	if err != nil {
		log.Fatal(err)
	}

	// For the blob, show each block (ID and size) that is a committed part of it.
	getBlock, err := blobURL.GetBlockList(ctx, BlockListAll, LeaseAccessConditions{})
	if err != nil {
		log.Fatal(err)
	}
	for _, block := range getBlock.CommittedBlocks {
		fmt.Printf("Block ID=%d, Size=%d\n", blockIDBase64ToInt(block.Name), block.Size)
	}

	// Download the blob in its entirety; download operations do not take blocks into account.
	// NOTE: For really large blobs, downloading them like allocates a lot of memory.
	get, err := blobURL.Download(ctx, 0, 0, BlobAccessConditions{}, false, ClientProvidedKeyOptions{})
	if err != nil {
		log.Fatal(err)
	}
	blobData := &bytes.Buffer{}
	reader := get.Body(RetryReaderOptions{})
	blobData.ReadFrom(reader)
	reader.Close() // The client must close the response body when finished with it
	fmt.Println(blobData)
}

// ExampleAppendBlobURL shows how to append data (in blocks) to an append blob.
// An append blob can have a maximum of 50,000 blocks; each block can have a maximum of 100MB.
// Therefore, the maximum size of an append blob is slightly more than 4.75 TB (100 MB X 50,000 blocks).
func ExampleAppendBlobURL() {
	// From the Azure portal, get your Storage account blob service URL endpoint.
	accountName, accountKey := accountInfo()

	// Create a ContainerURL object that wraps a soon-to-be-created blob's URL and a default pipeline.
	u, _ := url.Parse(fmt.Sprintf("https://%s.blob.core.windows.net/mycontainer/MyAppendBlob.txt", accountName))
	credential, err := NewSharedKeyCredential(accountName, accountKey)
	if err != nil {
		log.Fatal(err)
	}
	appendBlobURL := NewAppendBlobURL(*u, NewPipeline(credential, PipelineOptions{}))

	ctx := context.Background() // This example uses a never-expiring context
	_, err = appendBlobURL.Create(ctx, BlobHTTPHeaders{}, Metadata{}, BlobAccessConditions{}, nil, ClientProvidedKeyOptions{}, ImmutabilityPolicyOptions{})
	if err != nil {
		log.Fatal(err)
	}

	for i := 0; i < 5; i++ { // Append 5 blocks to the append blob
		_, err := appendBlobURL.AppendBlock(ctx, strings.NewReader(fmt.Sprintf("Appending block #%d\n", i)), AppendBlobAccessConditions{}, nil, ClientProvidedKeyOptions{})
		if err != nil {
			log.Fatal(err)
		}
	}

	// Download the entire append blob's contents and show it.
	get, err := appendBlobURL.Download(ctx, 0, 0, BlobAccessConditions{}, false, ClientProvidedKeyOptions{})
	if err != nil {
		log.Fatal(err)
	}
	b := bytes.Buffer{}
	reader := get.Body(RetryReaderOptions{})
	b.ReadFrom(reader)
	reader.Close() // The client must close the response body when finished with it
	fmt.Println(b.String())
}

// ExamplePageBlobURL shows how to manipulate a page blob with PageBlobURL.
// A page blob is a collection of 512-byte pages optimized for random read and write operations.
// The maximum size for a page blob is 8 TB.
func ExamplePageBlobURL() {
	// From the Azure portal, get your Storage account blob service URL endpoint.
	accountName, accountKey := accountInfo()

	// Create a ContainerURL object that wraps a soon-to-be-created blob's URL and a default pipeline.
	u, _ := url.Parse(fmt.Sprintf("https://%s.blob.core.windows.net/mycontainer/MyPageBlob.txt", accountName))
	credential, err := NewSharedKeyCredential(accountName, accountKey)
	if err != nil {
		log.Fatal(err)
	}
	blobURL := NewPageBlobURL(*u, NewPipeline(credential, PipelineOptions{}))

	ctx := context.Background() // This example uses a never-expiring context
	_, err = blobURL.Create(ctx, PageBlobPageBytes*4, 0, BlobHTTPHeaders{}, Metadata{}, BlobAccessConditions{}, DefaultPremiumBlobAccessTier, nil, ClientProvidedKeyOptions{}, ImmutabilityPolicyOptions{})
	if err != nil {
		log.Fatal(err)
	}

	page := [PageBlobPageBytes]byte{}
	copy(page[:], "Page 0")
	_, err = blobURL.UploadPages(ctx, 0*PageBlobPageBytes, bytes.NewReader(page[:]), PageBlobAccessConditions{}, nil, ClientProvidedKeyOptions{})
	if err != nil {
		log.Fatal(err)
	}

	copy(page[:], "Page 1")
	_, err = blobURL.UploadPages(ctx, 2*PageBlobPageBytes, bytes.NewReader(page[:]), PageBlobAccessConditions{}, nil, ClientProvidedKeyOptions{})
	if err != nil {
		log.Fatal(err)
	}

	getPages, err := blobURL.GetPageRanges(ctx, 0*PageBlobPageBytes, 10*PageBlobPageBytes, BlobAccessConditions{})
	if err != nil {
		log.Fatal(err)
	}
	for _, pr := range getPages.PageRange {
		fmt.Printf("Start=%d, End=%d\n", pr.Start, pr.End)
	}

	_, err = blobURL.ClearPages(ctx, 0*PageBlobPageBytes, 1*PageBlobPageBytes, PageBlobAccessConditions{}, ClientProvidedKeyOptions{})
	if err != nil {
		log.Fatal(err)
	}

	getPages, err = blobURL.GetPageRanges(ctx, 0*PageBlobPageBytes, 10*PageBlobPageBytes, BlobAccessConditions{})
	if err != nil {
		log.Fatal(err)
	}
	for _, pr := range getPages.PageRange {
		fmt.Printf("Start=%d, End=%d\n", pr.Start, pr.End)
	}

	get, err := blobURL.Download(ctx, 0, 0, BlobAccessConditions{}, false, ClientProvidedKeyOptions{})
	if err != nil {
		log.Fatal(err)
	}
	blobData := &bytes.Buffer{}
	reader := get.Body(RetryReaderOptions{})
	blobData.ReadFrom(reader)
	reader.Close() // The client must close the response body when finished with it
	fmt.Printf("%#v", blobData.Bytes())
}

// This example show how to create a blob, take a snapshot of it, update the base blob,
// read from the blob snapshot, list blobs with their snapshots, and hot to delete blob snapshots.
func Example_blobSnapshots() {
	// From the Azure portal, get your Storage account blob service URL endpoint.
	accountName, accountKey := accountInfo()

	// Create a ContainerURL object to a container where we'll create a blob and its snapshot.
	u, _ := url.Parse(fmt.Sprintf("https://%s.blob.core.windows.net/mycontainer", accountName))
	credential, err := NewSharedKeyCredential(accountName, accountKey)
	if err != nil {
		log.Fatal(err)
	}
	containerURL := NewContainerURL(*u, NewPipeline(credential, PipelineOptions{}))

	// Create a BlockBlobURL object to a blob in the container.
	baseBlobURL := containerURL.NewBlockBlobURL("Original.txt")

	ctx := context.Background() // This example uses a never-expiring context

	// Create the original blob:
	_, err = baseBlobURL.Upload(ctx, strings.NewReader("Some text"), BlobHTTPHeaders{}, Metadata{}, BlobAccessConditions{}, DefaultAccessTier, nil, ClientProvidedKeyOptions{}, ImmutabilityPolicyOptions{})
	if err != nil {
		log.Fatal(err)
	}

	// Create a snapshot of the original blob & save its timestamp:
	createSnapshot, err := baseBlobURL.CreateSnapshot(ctx, Metadata{}, BlobAccessConditions{}, ClientProvidedKeyOptions{})
	snapshot := createSnapshot.Snapshot()

	// Modify the original blob & show it:
	_, err = baseBlobURL.Upload(ctx, strings.NewReader("New text"), BlobHTTPHeaders{}, Metadata{}, BlobAccessConditions{}, DefaultAccessTier, nil, ClientProvidedKeyOptions{}, ImmutabilityPolicyOptions{})
	if err != nil {
		log.Fatal(err)
	}

	get, err := baseBlobURL.Download(ctx, 0, 0, BlobAccessConditions{}, false, ClientProvidedKeyOptions{})
	b := bytes.Buffer{}
	reader := get.Body(RetryReaderOptions{})
	b.ReadFrom(reader)
	reader.Close() // The client must close the response body when finished with it
	fmt.Println(b.String())

	// Show snapshot blob via original blob URI & snapshot time:
	snapshotBlobURL := baseBlobURL.WithSnapshot(snapshot)
	get, err = snapshotBlobURL.Download(ctx, 0, 0, BlobAccessConditions{}, false, ClientProvidedKeyOptions{})
	b.Reset()
	reader = get.Body(RetryReaderOptions{})
	b.ReadFrom(reader)
	reader.Close() // The client must close the response body when finished with it
	fmt.Println(b.String())

	// FYI: You can get the base blob URL from one of its snapshot by passing "" to WithSnapshot:
	baseBlobURL = snapshotBlobURL.WithSnapshot("")

	// Show all blobs in the container with their snapshots:
	// List the blob(s) in our container; since a container may hold millions of blobs, this is done 1 segment at a time.
	for marker := (Marker{}); marker.NotDone(); { // The parens around Marker{} are required to avoid compiler error.
		// Get a result segment starting with the blob indicated by the current Marker.
		listBlobs, err := containerURL.ListBlobsFlatSegment(ctx, marker, ListBlobsSegmentOptions{
			Details: BlobListingDetails{Snapshots: true}})
		if err != nil {
			log.Fatal(err)
		}
		// IMPORTANT: ListBlobs returns the start of the next segment; you MUST use this to get
		// the next segment (after processing the current result segment).
		marker = listBlobs.NextMarker

		// Process the blobs returned in this result segment (if the segment is empty, the loop body won't execute)
		for _, blobInfo := range listBlobs.Segment.BlobItems {
			snaptime := "N/A"
			if blobInfo.Snapshot != "" {
				snaptime = blobInfo.Snapshot
			}
			fmt.Printf("Blob name: %s, Snapshot: %s\n", blobInfo.Name, snaptime)
		}
	}

	// Promote read-only snapshot to writable base blob:
	_, err = baseBlobURL.StartCopyFromURL(ctx, snapshotBlobURL.URL(), Metadata{}, ModifiedAccessConditions{}, BlobAccessConditions{}, DefaultAccessTier, nil)
	if err != nil {
		log.Fatal(err)
	}

	// When calling Delete on a base blob:
	// DeleteSnapshotsOptionOnly deletes all the base blob's snapshots but not the base blob itself
	// DeleteSnapshotsOptionInclude deletes the base blob & all its snapshots.
	// DeleteSnapshotOptionNone produces an error if the base blob has any snapshots.
	_, err = baseBlobURL.Delete(ctx, DeleteSnapshotsOptionInclude, BlobAccessConditions{})
	if err != nil {
		log.Fatal(err)
	}
}

func Example_progressUploadDownload() {
	// Create a request pipeline using your Storage account's name and account key.
	accountName, accountKey := accountInfo()
	credential, err := NewSharedKeyCredential(accountName, accountKey)
	if err != nil {
		log.Fatal(err)
	}
	p := NewPipeline(credential, PipelineOptions{})

	// From the Azure portal, get your Storage account blob service URL endpoint.
	cURL, _ := url.Parse(fmt.Sprintf("https://%s.blob.core.windows.net/mycontainer", accountName))

	// Create an ServiceURL object that wraps the service URL and a request pipeline to making requests.
	containerURL := NewContainerURL(*cURL, p)

	ctx := context.Background() // This example uses a never-expiring context
	// Here's how to create a blob with HTTP headers and metadata (I'm using the same metadata that was put on the container):
	blobURL := containerURL.NewBlockBlobURL("Data.bin")

	// requestBody is the stream of data to write
	requestBody := strings.NewReader("Some text to write")

	// Wrap the request body in a RequestBodyProgress and pass a callback function for progress reporting.
	_, err = blobURL.Upload(ctx, pipeline.NewRequestBodyProgress(requestBody, func(bytesTransferred int64) {
		fmt.Printf("Wrote %d of %d bytes.", bytesTransferred, requestBody.Size())
	}), BlobHTTPHeaders{
		ContentType:        "text/html; charset=utf-8",
		ContentDisposition: "attachment",
	}, Metadata{}, BlobAccessConditions{}, DefaultAccessTier, nil, ClientProvidedKeyOptions{}, ImmutabilityPolicyOptions{})
	if err != nil {
		log.Fatal(err)
	}

	// Here's how to read the blob's data with progress reporting:
	get, err := blobURL.Download(ctx, 0, 0, BlobAccessConditions{}, false, ClientProvidedKeyOptions{})
	if err != nil {
		log.Fatal(err)
	}

	// Wrap the response body in a ResponseBodyProgress and pass a callback function for progress reporting.
	responseBody := pipeline.NewResponseBodyProgress(get.Body(RetryReaderOptions{}),
		func(bytesTransferred int64) {
			fmt.Printf("Read %d of %d bytes.", bytesTransferred, get.ContentLength())
		})

	downloadedData := &bytes.Buffer{}
	downloadedData.ReadFrom(responseBody)
	responseBody.Close() // The client must close the response body when finished with it
	// The downloaded blob data is in downloadData's buffer
}

// This example shows how to copy a source document on the Internet to a blob.
func ExampleBlobURL_startCopy() {
	// From the Azure portal, get your Storage account blob service URL endpoint.
	accountName, accountKey := accountInfo()

	// Create a ContainerURL object to a container where we'll create a blob and its snapshot.
	// Create a BlockBlobURL object to a blob in the container.
	u, _ := url.Parse(fmt.Sprintf("https://%s.blob.core.windows.net/mycontainer/CopiedBlob.bin", accountName))
	credential, err := NewSharedKeyCredential(accountName, accountKey)
	if err != nil {
		log.Fatal(err)
	}
	blobURL := NewBlobURL(*u, NewPipeline(credential, PipelineOptions{}))

	ctx := context.Background() // This example uses a never-expiring context

	src, _ := url.Parse("https://cdn2.auth0.com/docs/media/addons/azure_blob.svg")
	startCopy, err := blobURL.StartCopyFromURL(ctx, *src, nil, ModifiedAccessConditions{}, BlobAccessConditions{}, DefaultAccessTier, nil)
	if err != nil {
		log.Fatal(err)
	}

	copyID := startCopy.CopyID()
	copyStatus := startCopy.CopyStatus()
	for copyStatus == CopyStatusPending {
		time.Sleep(time.Second * 2)
		getMetadata, err := blobURL.GetProperties(ctx, BlobAccessConditions{}, ClientProvidedKeyOptions{})
		if err != nil {
			log.Fatal(err)
		}
		copyStatus = getMetadata.CopyStatus()
	}
	fmt.Printf("Copy from %s to %s: ID=%s, Status=%s\n", src.String(), blobURL, copyID, copyStatus)
}

// This example shows how to copy a large stream in blocks (chunks) to a block blob.
func ExampleUploadFileToBlockBlobAndDownloadItBack() {
	file, err := os.Open("BigFile.bin") // Open the file we want to upload
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()
	fileSize, err := file.Stat() // Get the size of the file (stream)
	if err != nil {
		log.Fatal(err)
	}

	// From the Azure portal, get your Storage account blob service URL endpoint.
	accountName, accountKey := accountInfo()

	// Create a BlockBlobURL object to a blob in the container (we assume the container already exists).
	u, _ := url.Parse(fmt.Sprintf("https://%s.blob.core.windows.net/mycontainer/BigBlockBlob.bin", accountName))
	credential, err := NewSharedKeyCredential(accountName, accountKey)
	if err != nil {
		log.Fatal(err)
	}
	blockBlobURL := NewBlockBlobURL(*u, NewPipeline(credential, PipelineOptions{}))

	ctx := context.Background() // This example uses a never-expiring context

	// Pass the Context, stream, stream size, block blob URL, and options to StreamToBlockBlob
	response, err := UploadFileToBlockBlob(ctx, file, blockBlobURL,
		UploadToBlockBlobOptions{
			// If Progress is non-nil, this function is called periodically as bytes are uploaded.
			Progress: func(bytesTransferred int64) {
				fmt.Printf("Uploaded %d of %d bytes.\n", bytesTransferred, fileSize.Size())
			},
		})
	if err != nil {
		log.Fatal(err)
	}
	_ = response // Avoid compiler's "declared and not used" error

	// Set up file to download the blob to
	destFileName := "BigFile-downloaded.bin"
	destFile, err := os.Create(destFileName)
	defer destFile.Close()

	// Perform download
	err = DownloadBlobToFile(context.Background(), blockBlobURL.BlobURL, 0, CountToEnd, destFile,
		DownloadFromBlobOptions{
			// If Progress is non-nil, this function is called periodically as bytes are uploaded.
			Progress: func(bytesTransferred int64) {
				fmt.Printf("Downloaded %d of %d bytes.\n", bytesTransferred, fileSize.Size())
			}})

	if err != nil {
		log.Fatal(err)
	}
}

// This example shows how to download a large stream with intelligent retries. Specifically, if
// the connection fails while reading, continuing to read from this stream initiates a new
// GetBlob call passing a range that starts from the last byte successfully read before the failure.
func ExampleBlobUrl_Download() {
	// From the Azure portal, get your Storage account blob service URL endpoint.
	accountName, accountKey := accountInfo()

	// Create a BlobURL object to a blob in the container (we assume the container & blob already exist).
	u, _ := url.Parse(fmt.Sprintf("https://%s.blob.core.windows.net/mycontainer/BigBlob.bin", accountName))
	credential, err := NewSharedKeyCredential(accountName, accountKey)
	if err != nil {
		log.Fatal(err)
	}
	blobURL := NewBlobURL(*u, NewPipeline(credential, PipelineOptions{}))

	contentLength := int64(0) // Used for progress reporting to report the total number of bytes being downloaded.

	// Download returns an intelligent retryable stream around a blob; it returns an io.ReadCloser.
	dr, err := blobURL.Download(context.TODO(), 0, -1, BlobAccessConditions{}, false, ClientProvidedKeyOptions{})
	if err != nil {
		log.Fatal(err)
	}
	rs := dr.Body(RetryReaderOptions{})

	// NewResponseBodyProgress wraps the GetRetryStream with progress reporting; it returns an io.ReadCloser.
	stream := pipeline.NewResponseBodyProgress(rs,
		func(bytesTransferred int64) {
			fmt.Printf("Downloaded %d of %d bytes.\n", bytesTransferred, contentLength)
		})
	defer stream.Close() // The client must close the response body when finished with it

	file, err := os.Create("BigFile.bin") // Create the file to hold the downloaded blob contents.
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()

	written, err := io.Copy(file, stream) // Write to the file by reading from the blob (with intelligent retries).
	if err != nil {
		log.Fatal(err)
	}
	_ = written // Avoid compiler's "declared and not used" error
}

func ExampleUploadStreamToBlockBlob() {
	// From the Azure portal, get your Storage account blob service URL endpoint.
	accountName, accountKey := accountInfo()

	// Create a BlockBlobURL object to a blob in the container (we assume the container already exists).
	u, _ := url.Parse(fmt.Sprintf("https://%s.blob.core.windows.net/mycontainer/BigBlockBlob.bin", accountName))
	credential, err := NewSharedKeyCredential(accountName, accountKey)
	if err != nil {
		log.Fatal(err)
	}
	blockBlobURL := NewBlockBlobURL(*u, NewPipeline(credential, PipelineOptions{}))

	ctx := context.Background() // This example uses a never-expiring context

	// Create some data to test the upload stream
	blobSize := 8 * 1024 * 1024
	data := make([]byte, blobSize)
	rand.Read(data)

	// Perform UploadStreamToBlockBlob
	bufferSize := 2 * 1024 * 1024 // Configure the size of the rotating buffers that are used when uploading
	maxBuffers := 3               // Configure the number of rotating buffers that are used when uploading
	_, err = UploadStreamToBlockBlob(ctx, bytes.NewReader(data), blockBlobURL,
		UploadStreamToBlockBlobOptions{BufferSize: bufferSize, MaxBuffers: maxBuffers})

	// Verify that upload was successful
	if err != nil {
		log.Fatal(err)
	}
}

// This example shows how to perform various lease operations on a container.
// The same lease operations can be performed on individual blobs as well.
// A lease on a container prevents it from being deleted by others, while a lease on a blob
// protects it from both modifications and deletions.
func ExampleLeaseContainer() {
	// From the Azure portal, get your Storage account's name and account key.
	accountName, accountKey := accountInfo()

	// Use your Storage account's name and key to create a credential object; this is used to access your account.
	credential, err := NewSharedKeyCredential(accountName, accountKey)
	if err != nil {
		log.Fatal(err)
	}

	// Create an ContainerURL object that wraps the container's URL and a default pipeline.
	u, _ := url.Parse(fmt.Sprintf("https://%s.blob.core.windows.net/mycontainer", accountName))
	containerURL := NewContainerURL(*u, NewPipeline(credential, PipelineOptions{}))

	// All operations allow you to specify a timeout via a Go context.Context object.
	ctx := context.Background() // This example uses a never-expiring context

	// Now acquire a lease on the container.
	// You can choose to pass an empty string for proposed ID so that the service automatically assigns one for you.
	acquireLeaseResponse, err := containerURL.AcquireLease(ctx, "", 60, ModifiedAccessConditions{})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("The container is leased for delete operations with lease ID", acquireLeaseResponse.LeaseID())

	// The container cannot be deleted without providing the lease ID.
	_, err = containerURL.Delete(ctx, ContainerAccessConditions{})
	if err == nil {
		log.Fatal("delete should have failed")
	}
	fmt.Println("The container cannot be deleted while there is an active lease")

	// We can release the lease now and the container can be deleted.
	_, err = containerURL.ReleaseLease(ctx, acquireLeaseResponse.LeaseID(), ModifiedAccessConditions{})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("The lease on the container is now released")

	// Acquire a lease again to perform other operations.
	acquireLeaseResponse, err = containerURL.AcquireLease(ctx, "", 60, ModifiedAccessConditions{})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("The container is leased again with lease ID", acquireLeaseResponse.LeaseID())

	// We can change the ID of an existing lease.
	// A lease ID can be any valid GUID string format.
	newLeaseID := newUUID()
	newLeaseID[0] = 1
	changeLeaseResponse, err := containerURL.ChangeLease(ctx, acquireLeaseResponse.LeaseID(), newLeaseID.String(), ModifiedAccessConditions{})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("The lease ID was changed to", changeLeaseResponse.LeaseID())

	// The lease can be renewed.
	renewLeaseResponse, err := containerURL.RenewLease(ctx, changeLeaseResponse.LeaseID(), ModifiedAccessConditions{})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("The lease was renewed with the same ID", renewLeaseResponse.LeaseID())

	// Finally, the lease can be broken and we could prevent others from acquiring a lease for a period of time
	_, err = containerURL.BreakLease(ctx, 60, ModifiedAccessConditions{})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("The lease was borken, and nobody can acquire a lease for 60 seconds")
}

// This example shows how to list blobs with hierarchy, by using a delimiter.
func ExampleListBlobsHierarchy() {
	// From the Azure portal, get your Storage account's name and account key.
	accountName, accountKey := accountInfo()

	// Use your Storage account's name and key to create a credential object; this is used to access your account.
	credential, err := NewSharedKeyCredential(accountName, accountKey)
	if err != nil {
		log.Fatal(err)
	}

	// Create an ContainerURL object that wraps the container's URL and a default pipeline.
	u, _ := url.Parse(fmt.Sprintf("https://%s.blob.core.windows.net/mycontainer", accountName))
	containerURL := NewContainerURL(*u, NewPipeline(credential, PipelineOptions{}))

	// All operations allow you to specify a timeout via a Go context.Context object.
	ctx := context.Background() // This example uses a never-expiring context

	// Create 4 blobs: 3 of which have a virtual directory
	blobNames := []string{"a/1", "a/2", "b/1", "boaty_mcboatface"}
	for _, blobName := range blobNames {
		blobURL := containerURL.NewBlockBlobURL(blobName)
		_, err := blobURL.Upload(ctx, strings.NewReader("test"), BlobHTTPHeaders{}, nil, BlobAccessConditions{}, DefaultAccessTier, nil, ClientProvidedKeyOptions{}, ImmutabilityPolicyOptions{})

		if err != nil {
			log.Fatal("an error occurred while creating blobs for the example setup")
		}
	}

	// Perform a listing operation on blobs with hierarchy
	resp, err := containerURL.ListBlobsHierarchySegment(ctx, Marker{}, "/", ListBlobsSegmentOptions{})
	if err != nil {
		log.Fatal("an error occurred while listing blobs")
	}

	// When a delimiter is used, the listing operation returns BlobPrefix elements that acts as
	// a placeholder for all blobs whose names begin with the same substring up to the appearance of the delimiter character.
	// In our example, this means that a/ and b/ will be both returned
	fmt.Println("======First listing=====")
	for _, blobPrefix := range resp.Segment.BlobPrefixes {
		fmt.Println("The blob prefix with name", blobPrefix.Name, "was returned in the listing operation")
	}

	// The blobs that do not contain the delimiter are still returned
	for _, blob := range resp.Segment.BlobItems {
		fmt.Println("The blob with name", blob.Name, "was returned in the listing operation")
	}

	// For the prefixes that are returned, we can perform another listing operation on them, to see their contents
	resp, err = containerURL.ListBlobsHierarchySegment(ctx, Marker{}, "/", ListBlobsSegmentOptions{
		Prefix: "a/",
	})
	if err != nil {
		log.Fatal("an error occurred while listing blobs")
	}

	// This time, there is no blob prefix returned, since nothing under a/ has another / in its name.
	// In other words, in the virtual directory of a/, there aren't any sub-level virtual directory.
	fmt.Println("======Second listing=====")
	fmt.Println("No prefiex should be returned now, and the actual count is", len(resp.Segment.BlobPrefixes))

	// The blobs a/1 and a/2 should be returned
	for _, blob := range resp.Segment.BlobItems {
		fmt.Println("The blob with name", blob.Name, "was returned in the listing operation")
	}

	// Delete the blobs created by this example
	for _, blobName := range blobNames {
		blobURL := containerURL.NewBlockBlobURL(blobName)
		_, err := blobURL.Delete(ctx, DeleteSnapshotsOptionNone, BlobAccessConditions{})

		if err != nil {
			log.Fatal("an error occurred while deleting the blobs created by the example")
		}
	}
}

func fetchMSIToken(applicationID string, identityResourceID string, resource string, callbacks ...adal.TokenRefreshCallback) (*adal.ServicePrincipalToken, error) {
	// Both application id and identityResourceId cannot be present at the same time.
	if applicationID != "" && identityResourceID != "" {
		return nil, fmt.Errorf("didn't expect applicationID and identityResourceID at same time")
	}

	// msiEndpoint is the well known endpoint for getting MSI authentications tokens
	// msiEndpoint := "http://169.254.169.254/metadata/identity/oauth2/token" for production Jobs
	msiEndpoint, _ := adal.GetMSIVMEndpoint()

	var spt *adal.ServicePrincipalToken
	var err error

	// both can be empty, systemAssignedMSI scenario
	if applicationID == "" && identityResourceID == "" {
		spt, err = adal.NewServicePrincipalTokenFromMSI(msiEndpoint, resource, callbacks...)
	}

	// msi login with clientID
	if applicationID != "" {
		spt, err = adal.NewServicePrincipalTokenFromMSIWithUserAssignedID(msiEndpoint, resource, applicationID, callbacks...)
	}

	// msi login with resourceID
	if identityResourceID != "" {
		spt, err = adal.NewServicePrincipalTokenFromMSIWithIdentityResourceID(msiEndpoint, resource, identityResourceID, callbacks...)
	}

	if err != nil {
		return nil, err
	}

	return spt, spt.Refresh()
}

func getOAuthToken(applicationID, identityResourceID, resource string, callbacks ...adal.TokenRefreshCallback) (*TokenCredential, error) {
	spt, err := fetchMSIToken(applicationID, identityResourceID, resource, callbacks...)
	if err != nil {
		log.Fatal(err)
	}

	// Refresh obtains a fresh token
	err = spt.Refresh()
	if err != nil {
		log.Fatal(err)
	}

	tc := NewTokenCredential(spt.Token().AccessToken, func(tc TokenCredential) time.Duration {
		err := spt.Refresh()
		if err != nil {
			// something went wrong, prevent the refresher from being triggered again
			return 0
		}

		// set the new token value
		tc.SetToken(spt.Token().AccessToken)

		// get the next token slightly before the current one expires
		return time.Until(spt.Token().Expires()) - 10*time.Second
	})

	return &tc, nil
}

func ExampleMSILogin() {
	var accountName string
	// Use the azure resource id of user assigned identity when creating the token.
	// identityResourceID := "/subscriptions/{subscriptionID}/resourceGroups/testGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test-identity"
	// resource := "https://resource"
	var applicationID, identityResourceID, resource string
	var err error

	callbacks := func(token adal.Token) error { return nil }

	tokenCredentials, err := getOAuthToken(applicationID, identityResourceID, resource, callbacks)
	if err != nil {
		log.Fatal(err)
	}
	// Create pipeline to handle requests
	p := NewPipeline(*tokenCredentials, PipelineOptions{})
	blobPrimaryURL, _ := url.Parse("https://" + accountName + ".blob.core.windows.net/")
	// Generate a blob service URL
	bsu := NewServiceURL(*blobPrimaryURL, p)

	// Create container & upload sample data
	containerName := generateContainerName()
	containerURL := bsu.NewContainerURL(containerName)
	_, err = containerURL.Create(ctx, Metadata{}, PublicAccessNone)
	defer containerURL.Delete(ctx, ContainerAccessConditions{})
	if err != nil {
		log.Fatal(err)
	}

	// Inside the container, create a test blob with random data.
	blobName := generateBlobName()
	blobURL := containerURL.NewBlockBlobURL(blobName)
	data := "Hello World!"
	uploadResp, err := blobURL.Upload(ctx, strings.NewReader(data), BlobHTTPHeaders{ContentType: "text/plain"}, Metadata{}, BlobAccessConditions{}, DefaultAccessTier, nil, ClientProvidedKeyOptions{}, ImmutabilityPolicyOptions{})
	if err != nil || uploadResp.StatusCode() != 201 {
		log.Fatal(err)
	}

	// Download data via User Delegation SAS URL; must succeed
	downloadResp, err := blobURL.Download(ctx, 0, 0, BlobAccessConditions{}, false, ClientProvidedKeyOptions{})
	if err != nil {
		log.Fatal(err)
	}
	downloadedData := &bytes.Buffer{}
	reader := downloadResp.Body(RetryReaderOptions{})
	_, err = downloadedData.ReadFrom(reader)
	if err != nil {
		log.Fatal(err)
	}
	err = reader.Close()
	if err != nil {
		log.Fatal(err)
	}

	// Verify the content
	reflect.DeepEqual(data, downloadedData)

	// Delete the item using the User Delegation SAS URL; must succeed
	_, err = blobURL.Delete(ctx, DeleteSnapshotsOptionInclude, BlobAccessConditions{})
	if err != nil {
		log.Fatal(err)
	}
}