Friday, April 19, 2024
HomeGolangBe part of URL path parts in Go (Golang)

Be part of URL path parts in Go (Golang)



In internet improvement, a typical process is to mix completely different URL parts into one, for instance, in case you are creating a REST API shopper and need to concatenate a given hostname with relative paths to endpoints. In Go since model 1.19 that is very straightforward, simply use the url.JoinPath() operate from the internet/url bundle. Alternatively, you can too use the JoinPath() methodology of the URL struct from the identical bundle.

These capabilities will help you keep away from widespread errors that may come up when manually concatenating path parts, for instance, double slashes or lacking slashes within the remaining URL, which may trigger surprising conduct.

Examples

The fundamental use of the url.JoinPath() operate is easy. You merely cross the bottom URL as the primary argument, and cross additional parts of the URL you need to be a part of to the bottom one as subsequent arguments. The signature of the operate seems to be as follows:

func JoinPath(base string, elem ...string) (end result string, err error)

The url.JoinPath() operate robotically takes care of the proper formatting of the ensuing URL, guaranteeing that it’s well-formatted with out redundant / or ../ characters.

Check out the instance under to see the way it works:

bundle major

import (
    "fmt"
    "log"
    "internet/url"
)

func major() {
    hostname := "https://gosamples.dev/"
    path1 := "//join-url-elements//"
    path2 := "/foo/"
    path3 := "//bar"

    end result, err := url.JoinPath(hostname, path1, path2, path3)
    if err != nil {
        log.Deadly(err)
    }

    fmt.Println(end result)
}

Within the output you’ll get the ensuing URL cleaned of redundant parts as a string:

https://gosamples.dev/join-url-elements/foo/bar

Alternatively, you probably have a URL as a url.URL kind and in addition need to get a url.URL construction because of this, you should utilize the JoinPath() methodology, passing as arguments solely the brand new parts you need to be a part of to the prevailing URL. The tactic works precisely the identical because the url.JoinPath() operate from the earlier instance:

bundle major

import (
    "fmt"
    "log"
    "internet/url"
)

func major() {
    gosamplesURL, err := url.Parse("https://gosamples.dev/")
    if err != nil {
        log.Deadly(err)
    }
    path1 := "//join-url-elements//"
    path2 := "/foo/"
    path3 := "//bar"

    newGosamplesURL := gosamplesURL.JoinPath(path1, path2, path3)
    if err != nil {
        log.Deadly(err)
    }

    fmt.Println(newGosamplesURL)
}

Within the output, you’ll get the ensuing URL cleaned of pointless parts as a url.URL struct:

https://gosamples.dev/join-url-elements/foo/bar

And that’s it. Completely satisfied coding! 👨‍💻✨🎉

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments