Golang : How to get URL port?
From the previous tutorial on how to break down a URL string, a reader emailed me wanting to know if there is a way to get the port number directly from the raw URL?
For example :
rawURL := "http://username:password@searchengine.com:8080/testpath/?q=socketloop.com#TestFunc"
and get the port number 8080 with a function.
From my research, there is a function in the net
package ... the net/SplitHostPort()
function is able to do just that, but with the condition that the URL is in the form of "host:port"
, "[host]:port"
or "[ipv6-host%zone]:port"
To use net/SplitHostPort()
function on rawURL will produce this error message :
too many colons in address http://username:password@searchengine.com:8080/testpath/?q=socketloop.com#TestFunc
and therefore it is recommended to parse the rawURL first
// Parse the URL and ensure there are no errors.
url, err := url.Parse(rawURL)
if err != nil {
panic(err)
}
and apply the SplitHostPort() function on url.Host
shost, sport, err := net.SplitHostPort(url.Host)
fmt.Println("Split Host is : ", shost)
fmt.Println("Split Port is : ", sport)
Here's complete code :
package main
import (
"fmt"
"net"
"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)
// or use net.SplitHostPort
// won't work with rawURL string
shost, sport, err := net.SplitHostPort(url.Host)
fmt.Println("Split Host is : ", shost)
fmt.Println("Split Port is : ", sport)
if err != nil {
fmt.Println(err)
}
// 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
Split Host is : searchengine.com
Split Port is : 8080
Path : /testpath/
Raw Query q=socketloop.com
Fragment : TestFunc
Reference :
See also : Golang : Parsing or breaking down URL
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
+18.1k Golang : How to get hour, minute, second from time?
+7.4k Gogland : Where to put source code files in package directory for rookie
+8.6k Golang : Find network service name from given port and protocol
+16.3k Golang : Merge video(OpenCV) and audio(PortAudio) into a mp4 file
+30k Golang : Generate random string
+9.4k Javascript : Read/parse JSON data from HTTP response
+10.7k Golang : Create Temporary File
+6.7k Golang : Calculate BMI and risk category
+5.8k PageSpeed : Clear or flush cache on web server
+28.9k Golang : missing Git command
+5.9k Golang : Get missing location after unmarshal binary and gob decode time.
+11.2k Golang : Handle API query by curl with Gorilla Queries example