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:[email protected]: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:[email protected]: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
+13.1k Golang : Read from buffered reader until specific number of bytes
+10.3k Golang : Resolve domain name to IP4 and IP6 addresses.
+5.1k Javascript : How to loop over and parse JSON data?
+17.7k Golang : Put UTF8 text on OpenCV video capture image frame
+12.9k Golang : How to get a user home directory path?
+14.6k Golang : How to check for empty array string or string?
+8.2k PHP : How to parse ElasticSearch JSON ?
+10.2k Golang : Generate random integer or float number
+20.1k Nginx + FastCGI + Go Setup.
+9.1k Golang : Terminate-stay-resident or daemonize your program?
+13.3k Golang : Set image canvas or background to transparent
+18.9k Mac OSX : Homebrew and Golang