[英]Extract resource-id from ARN
I saw in AWS documentation that ARN formats are:我在 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
I'm trying to fetch the resource-id
from the ARN.我正在尝试从 ARN 中获取
resource-id
。
The following code works, but ugly...以下代码有效,但丑陋......
I'm searching for how to improve it:我正在寻找如何改进它:
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
}
I would suggest a simple regular expression:我会建议一个简单的正则表达式:
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"))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.