英文:
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
}
英文:
I saw in AWS documentation that ARN formats are:
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.
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
}
答案1
得分: 2
我建议使用一个简单的正则表达式:
package main
import (
"fmt"
"regexp"
)
func main() {
// 编译表达式,通常在初始化时进行
// 使用原始字符串避免需要转义反斜杠
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"))
}
在这里查看演示:链接
英文:
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"))
}
See the demo here
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论