Home > Software engineering >  Retrieve first directory in URL-like string in Go
Retrieve first directory in URL-like string in Go

Time:12-15

I am trying to obtain the first directory in an URL-like string like this: "/blog/:year/:daynum/:postname". I thought splitting it, then retrieving the first directory, would be this simple. But it returns square brackets surrounding the string even though it's not a slice. How can I get that first directory? (I am guaranteed that the string starts with a "/" followed by a valid directory designation and that contains both a leading directory and a string using those permalink properties).

What's the best way to parse out that first directory?

package main
import (
    "fmt"
    "strings"
)
// Retrieve the first directory in the URL-like
// string passed in
func firstDir(permalink string) string {
    split := strings.Split(permalink, "/")
    return string(fmt.Sprint((split[0:2])))
}
func main() {
    permalink := "/blog/:year/:daynum/:postname"
    dir := firstDir(permalink)
    fmt.Printf("leading dir is: %s.", dir)
    // Prints NOT "blog" but "[ blog]".
}

CodePudding user response:

Since you said:"(I am guaranteed that the string starts with a "/" followed by a valid directory designation and that contains both a leading directory and a string using those permalink properties)"

Then simply use split[1] to get the root directory.

package main

import (
    "fmt"
    "os"
    "strings"
)

func firstDir(permalink string) string {
    split := strings.Split(permalink, string(os.PathSeparator))
    return split[1]
}
func main() {
    permalink := "/blog/:year/:daynum/:postname"
    dir := firstDir(permalink)
    fmt.Printf("leading dir is: %s.", dir)
    // Prints "blog".
}

https://go.dev/play/p/hCHnrDIsWYE

  •  Tags:  
  • go
  • Related