1

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.

2 Answers 2

4

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 
Sign up to request clarification or add additional context in comments.

Comments

3

You can try

u, _ := url.Parse("https://example.com/user/1000") val := fmt.Sprintf("%s://%s", u.Scheme, u.Host) 

The following may be more useful in the general case.

rawURL := "https://user:pass@localhost:8080/user/1000/profile?p=n#abc" u, _ := url.Parse(rawURL) psw, pswSet := u.User.Password() for _, d := range []struct { actual any expected any }{ {u.Scheme, "https"}, {u.User.Username(), "user"}, {psw, "pass"}, {pswSet, true}, {u.Host, "localhost:8080"}, {u.Path, "/user/1000/profile"}, {u.Port(), "8080"}, {u.RawPath, ""}, {u.RawQuery, "p=n"}, {u.Fragment, "abc"}, {u.RawFragment, ""}, {u.RequestURI(), "/user/1000/profile?p=n"}, {u.String(), rawURL}, {fmt.Sprintf("%s://%s", u.Scheme, u.Host), "https://localhost:8080"}, } { if d.actual != d.expected { t.Fatalf("%s\n%s\n", d.actual, d.expected) } } 

go-playground

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.