Home > Mobile >  Replace multiple ids in a path after validation [Golang]
Replace multiple ids in a path after validation [Golang]

Time:03-12

I have a path delimited by /and an expectation to have multiple ids I want to replace with a constant value. The issue I am facing is that once it validates the first id, it performs the replacement and stops. My assumption is that I should be having some sort of do while in Golang (see this resource - I know there is no such a construct in Go) and I have attempted at using:

for true {       
      // do something
} 

but still only the first id is replaced. Any idea? Thank you

Here is my Go Playground example with the original implementation

CodePudding user response:

The problem is you early return after first match. Since you iterating parts of path you should assign result of strings.Replace() to a variable and return after for loop. Assign to path instead of returning and it should work as expected.

func SubstituteById(path string, repl string) string {
    ids := strings.Split(path, "/")
    for _, id := range ids {
        if fastuuid.ValidHex128(id) {
            path = strings.Replace(path, id, repl, -1)
        }
    }
    return path
}
  • Related