从 ARN 中提取资源 ID
Extract resource-id from ARN
我在 AWS 文档中看到 ARN 格式是:
arn:partition:service:region:account-id:resource-id
arn:partition:service:region:account-id:resource-type/resource-id
arn:partition:service:region:account-id:resource-type:resource-id
我正在尝试从 ARN 中获取 resource-id
。
下面的代码可以工作,但是很难看...
我正在寻找改进方法:
func GetResourceNameFromARN(roleARN string) string {
if parsedARN, err := arn.Parse(roleARN); err == nil {
return parsedARN.Resource
}
return ""
}
func extractResourceId(arn string) string {
resource := GetResourceNameFromARN(arn)
switch len(strings.Split(resource, "/")) {
case 1:
switch len(strings.Split(resource, ":")) {
case 2:
return strings.Split(resource, ":")[1]
}
case 2:
return strings.Split(resource, "/")[1]
}
return resource
}
我建议使用一个简单的正则表达式:
package main
import (
"fmt"
"regexp"
)
func main() {
// Compile the expression once, usually at init time.
// Use raw strings to avoid having to quote the backslashes.
var validID = regexp.MustCompile(`[^:/]*$`)
fmt.Println(validID.FindString("arn:partition:service:region:account-id:resource-id"))
fmt.Println(validID.FindString("arn:partition:service:region:account-id:resource-type/resource-id"))
fmt.Println(validID.FindString("arn:partition:service:region:account-id:resource-type:resource-id"))
}
观看演示 here
我在 AWS 文档中看到 ARN 格式是:
arn:partition:service:region:account-id:resource-id
arn:partition:service:region:account-id:resource-type/resource-id
arn:partition:service:region:account-id:resource-type:resource-id
我正在尝试从 ARN 中获取 resource-id
。
下面的代码可以工作,但是很难看...
我正在寻找改进方法:
func GetResourceNameFromARN(roleARN string) string {
if parsedARN, err := arn.Parse(roleARN); err == nil {
return parsedARN.Resource
}
return ""
}
func extractResourceId(arn string) string {
resource := GetResourceNameFromARN(arn)
switch len(strings.Split(resource, "/")) {
case 1:
switch len(strings.Split(resource, ":")) {
case 2:
return strings.Split(resource, ":")[1]
}
case 2:
return strings.Split(resource, "/")[1]
}
return resource
}
我建议使用一个简单的正则表达式:
package main
import (
"fmt"
"regexp"
)
func main() {
// Compile the expression once, usually at init time.
// Use raw strings to avoid having to quote the backslashes.
var validID = regexp.MustCompile(`[^:/]*$`)
fmt.Println(validID.FindString("arn:partition:service:region:account-id:resource-id"))
fmt.Println(validID.FindString("arn:partition:service:region:account-id:resource-type/resource-id"))
fmt.Println(validID.FindString("arn:partition:service:region:account-id:resource-type:resource-id"))
}
观看演示 here