Home > Blockchain >  How to extract base url using golang
How to extract base url using golang

Time:05-26

Given a url string, how to retrieve only the base url (i.e. protocol://host:port)

For example

https://example.com/user/1000 => https://example.com

https://localhost:8080/user/1000/profile => https://localhost:8080

I've tried parsing the url with url.Parse() but the net/url doesn't seem to have a method that returns the base url. I could try appending the individual parts of url to get the base url but I just wanted to check if there are any better alternatives to this.

CodePudding user response:

I would parse it using url.Parse(), and zero the fields you don't want in the result, namely Path, RawQuery and Fragment. Then the result (base URL) can be acquired using URL.String().

For example:

u, err := url.Parse("https://user@pass:localhost:8080/user/1000/profile?p=n#abc")
if err != nil {
    panic(err)
}
fmt.Println(u)
u.Path = ""
u.RawQuery = ""
u.Fragment = ""
fmt.Println(u)
fmt.Println(u.String())

This will output (try it on the Go Playground):

https://user@pass:localhost:8080/user/1000/profile?p=n#abc
https://user@pass:localhost:8080
https://user@pass:localhost:8080
  • Related