简体   繁体   中英

Extract resource-id from ARN

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
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM