| 1 | package blobs |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "net/url" |
| 6 | "strings" |
| 7 | |
| 8 | "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" |
| 9 | ) |
| 10 | |
| 11 | // GetResourceID returns the Resource ID for the given Blob |
| 12 | // This can be useful when, for example, you're using this as a unique identifier |
| 13 | func (client Client) GetResourceID(accountName, containerName, blobName string) string { |
| 14 | domain := endpoints.GetBlobEndpoint(client.BaseURI, accountName) |
| 15 | return fmt.Sprintf("%s/%s/%s", domain, containerName, blobName) |
| 16 | } |
| 17 | |
| 18 | type ResourceID struct { |
| 19 | AccountName string |
| 20 | ContainerName string |
| 21 | BlobName string |
| 22 | } |
| 23 | |
| 24 | // ParseResourceID parses the Resource ID and returns an object which can be used |
| 25 | // to interact with the Blob Resource |
| 26 | func ParseResourceID(id string) (*ResourceID, error) { |
| 27 | // example: https://foo.blob.core.windows.net/Bar/example.vhd |
| 28 | if id == "" { |
| 29 | return nil, fmt.Errorf("`id` was empty") |
| 30 | } |
| 31 | |
| 32 | uri, err := url.Parse(id) |
| 33 | if err != nil { |
| 34 | return nil, fmt.Errorf("Error parsing ID as a URL: %s", err) |
| 35 | } |
| 36 | |
| 37 | accountName, err := endpoints.GetAccountNameFromEndpoint(uri.Host) |
| 38 | if err != nil { |
| 39 | return nil, fmt.Errorf("Error parsing Account Name: %s", err) |
| 40 | } |
| 41 | |
| 42 | path := strings.TrimPrefix(uri.Path, "/") |
| 43 | segments := strings.Split(path, "/") |
| 44 | if len(segments) == 0 { |
| 45 | return nil, fmt.Errorf("Expected the path to contain segments but got none") |
| 46 | } |
| 47 | |
| 48 | containerName := segments[0] |
| 49 | blobName := strings.TrimPrefix(path, containerName) |
| 50 | blobName = strings.TrimPrefix(blobName, "/") |
| 51 | return &ResourceID{ |
| 52 | AccountName: *accountName, |
| 53 | ContainerName: containerName, |
| 54 | BlobName: blobName, |
| 55 | }, nil |
| 56 | } |