package main
import (
"fmt"
"net"
"net/url"
)
func main() {
s := "mysql://user:pass@host.com:3306/path?key=value#fragment"
u, err := url.Parse(s)
if err != nil {
panic(err)
}
fmt.Println("Scheme: " + u.Scheme)
fmt.Println("Username: " + u.User.Username())
p, _ := u.User.Password()
fmt.Println("Password: " + p)
fmt.Println("Host with port: " + u.Host)
host, port, err := net.SplitHostPort(u.Host)
if err != nil {
panic(err)
}
fmt.Println("Host: " + host)
fmt.Println("Port: " + port)
fmt.Println("Path: " + u.Path)
fmt.Println("Fragment: " + u.Fragment)
fmt.Println("Raw query: " + u.RawQuery)
m, err := url.ParseQuery(u.RawQuery)
if err != nil {
panic(err)
}
fmt.Println("Value: " + m["key"][0])
}
// $ go run main.go
// Scheme: mysql
// Username: user
// Password: pass
// Host with port: host.com:3306
// Host: host.com
// Port: 3306
// Path: /path
// Fragment: fragment
// Raw query: key=value
// Value: value
Here is an example of how to parse URL, which includes a scheme, authentication info, host, port, path, query params, and query fragment.