Golang : Parsing or breaking down URL
Golang provides an easy way to consume and parse URL. It has a very neat package ( http://golang.org/pkg/net/url ) that deals with URL and allow developers to break down the URL into meaningful fragments for processing. The codes below will demonstrate how easy it is to parse a raw URL.
package main
import (
"fmt"
"net/url"
"strings"
)
func main() {
rawURL := "http://username:password@searchengine.com:8080/testpath/?q=socketloop.com#TestFunc"
fmt.Println("URL : ", rawURL)
// Parse the URL and ensure there are no errors.
url, err := url.Parse(rawURL)
if err != nil {
panic(err)
}
// see http://golang.org/pkg/net/url/#URL
// scheme://[userinfo@]host/path[?query][#fragment]
// get the Scheme
fmt.Println("Scheme : ", url.Scheme)
// get the User information
fmt.Println("Username : ", url.User.Username())
password, set := url.User.Password()
fmt.Println("Password : ", password)
fmt.Println("Password set : ", set)
// get the Host
fmt.Println("Raw host : ", url.Host)
// to get the Port number, split the Host
hostport := strings.Split(url.Host, ":")
host := hostport[0]
port := hostport[1]
fmt.Println("Host : ", host)
fmt.Println("Port : ", port)
// get the Path
fmt.Println("Path : ", url.Path)
// get the RawQuery
fmt.Println("Raw Query ", url.RawQuery)
// get the fragment
fmt.Println("Fragment : ", url.Fragment)
}
Output :
URL : http://username:password@searchengine.com:8080/testpath/?q=socketloop.com#TestFunc
Scheme : http
Username : username
Password : password
Password set : true
Raw host : searchengine.com:8080
Host : searchengine.com
Port : 8080
Path : /testpath/
Raw Query q=socketloop.com
Fragment : TestFunc
See also : Golang : Get URI segments by number and assign as variable example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+28.7k Golang : Get first few and last few characters from string
+12.2k Golang : Forwarding a local port to a remote server example
+39.7k Golang : Convert to io.ReadSeeker type
+17.4k Golang : Read data from config file and assign to variables
+9.8k Golang : Get escape characters \u form from unicode characters
+29.2k Golang : Login(Authenticate) with Facebook example
+6k Golang : How to get capacity of a slice or array?
+10.6k Golang : Natural string sorting example
+13.2k Golang : Get user input until a command or receive a word to stop
+6k Golang & Javascript : How to save cropped image to file on server
+8.8k Golang : Simple histogram example
+5.3k PHP : Convert string to timestamp or datestamp before storing to database(MariaDB/MySQL)