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
+19.2k Golang : How to Set or Add Header http.ResponseWriter?
+9.4k Golang : interface - when and where to use examples
+8.1k Useful methods to access blocked websites
+5.7k Fontello : How to load and use fonts?
+6.7k Golang : Gargish-English language translator
+5.4k Unix/Linux/MacOSx : Get local IP address
+11.4k Golang : How to detect a server/machine network interface capabilities?
+8.7k Golang : Build and compile multiple source files
+14.6k Golang : Search folders for file recursively with wildcard support
+8.1k Golang : Convert word to its plural form example
+18.9k Mac OSX : Homebrew and Golang
+11.8k Golang : Pagination with go-paginator configuration example