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
+6.8k Golang : Find the longest line of text example
+8.4k Golang : How to check if input string is a word?
+7.5k Gogland : Single File versus Go Application Run Configurations
+12.2k Golang : List running EC2 instances and descriptions
+8.2k Golang : Reverse text lines or flip line order example
+7.5k Golang : How to handle file size larger than available memory panic issue
+12.2k Golang : calculate elapsed run time
+12.6k Golang : Exit, terminating or aborting a program
+22.1k Golang : Repeat a character by multiple of x factor
+30.8k error: trying to remove "yum", which is protected
+15.9k Golang : Get file permission
+6.4k PHP : Proper way to get UTF-8 character or string length