Share & grow the world's code base!

Delve into a community where programmers unite to discover code snippets, exchange skills, and enhance their programming proficiency. With abundant resources and a supportive community, you'll find everything essential for your growth and success.

1 snippets
  • Parse URL in Go

    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.