1package files 2 3import ( 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 File 12// This can be useful when, for example, you're using this as a unique identifier 13func (client Client) GetResourceID(accountName, shareName, directoryName, filePath string) string { 14 domain := endpoints.GetFileEndpoint(client.BaseURI, accountName) 15 return fmt.Sprintf("%s/%s/%s/%s", domain, shareName, directoryName, filePath) 16} 17 18type ResourceID struct { 19 AccountName string 20 DirectoryName string 21 FileName string 22 ShareName string 23} 24 25// ParseResourceID parses the specified Resource ID and returns an object 26// which can be used to interact with Files within a Storage Share. 27func ParseResourceID(id string) (*ResourceID, error) { 28 // example: https://account1.file.core.chinacloudapi.cn/share1/directory1/file1.txt 29 // example: https://account1.file.core.chinacloudapi.cn/share1/directory1/directory2/file1.txt 30 31 if id == "" { 32 return nil, fmt.Errorf("`id` was empty") 33 } 34 35 uri, err := url.Parse(id) 36 if err != nil { 37 return nil, fmt.Errorf("Error parsing ID as a URL: %s", err) 38 } 39 40 accountName, err := endpoints.GetAccountNameFromEndpoint(uri.Host) 41 if err != nil { 42 return nil, fmt.Errorf("Error parsing Account Name: %s", err) 43 } 44 45 path := strings.TrimPrefix(uri.Path, "/") 46 segments := strings.Split(path, "/") 47 if len(segments) == 0 { 48 return nil, fmt.Errorf("Expected the path to contain segments but got none") 49 } 50 51 shareName := segments[0] 52 fileName := segments[len(segments)-1] 53 54 directoryName := strings.TrimPrefix(path, shareName) 55 directoryName = strings.TrimPrefix(directoryName, "/") 56 directoryName = strings.TrimSuffix(directoryName, fileName) 57 directoryName = strings.TrimSuffix(directoryName, "/") 58 return &ResourceID{ 59 AccountName: *accountName, 60 ShareName: shareName, 61 DirectoryName: directoryName, 62 FileName: fileName, 63 }, nil 64} 65