Introduction
Go language has good support for URL parsing. URL contains a scheme, authentication info, host, port, path, query params, and query fragment. We can use the parsing URL function url.Parse from the net/url package of Golang to parses a given URL and returns the URI object.
The net/url package has the required functions like Scheme, User, Host, Path, RawQuery, etc.
Go URL Parsing Example
Example
package main
import (
"fmt"
"net"
"net/url"
)
func main(){
link:="golang://user:pass@localhost.com:9000/server/page1?k1=v1&k2=v2#X"
u,err:=url.Parse(link)
if err!=nil{
panic(err)
}
fmt.Println(u.Scheme)
fmt.Println(u.User)
fmt.Println(u.User.Username())
pass, _:=u.User.Password()
fmt.Println(pass)
fmt.Println(u.Host)
host, port, _:=net.SplitHostPort(u.Host)
fmt.Println(host)
fmt.Println(port)
fmt.Println(u.Path)
fmt.Println(u.Fragment)
fmt.Println(u.RawQuery)
m,_:= url.ParseQuery(u.RawQuery)
fmt.Println(m)
fmt.Println(m["k2"][0])
}
Output
golang
user:pass
user
pass
localhost.com:9000
localhost.com
9000
/server/page1
X
k1=v1&k2=v2
map[k1:[v1] k2:[v2]]
v2
In the above code, The u.Scheme returns the Schema of the URL. The 'User' contains all authentication info; we called Username and Password on this for individual values. The 'Host' contains both the hostname and the port if present. We used SplitHostPort to extract them. We also extracted the path using u.path and the fragment after the # using u.fragment. We used 'RawQuery' to get query parameters in a string of k=v format. We also parsed query parameters into a map using 'ParseQuery'. The parsed query param maps are from strings to slices of strings.




