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