URL parsing in Go

1 min read
In this small blog we will see how we can parse a raw url and extract all the important info from it. We will use Go’s net/url library for this.
Let’s understand different components of URL.
https :// username:password @ example.com:8080 /url-parsing-in-GO? go=best # section
https - Scheme
username:password - User
example.com:8080 - Host ( host - example.com & port- 8080 )
/url-parsing-in-GO - Path
go=best - Query ( query is like key:value pairs after
?
sign )section - Fragment(after
#
sign)
package main
import (
"fmt"
"log"
"net"
"net/url"
)
func main () {
rawURL := "https://username:password@example.com:8080/url-parsing-in-GO?go=best#section"
mainURL, err := url.Parse(rawURL)
if err != nil {
log.Fatal(err)
}
fmt.Println("Scheme:", mainURL.Scheme)
fmt.Println("User: ", mainURL.User)
fmt.Println("Host: ", mainURL.Host)
fmt.Println("Path: ", mainURL.Path)
fmt.Println("Fragment: ", mainURL.Fragment)
fmt.Println("Query: ", mainURL.RawQuery)
host, port, _ := net.SplitHostPort(mainURL.Host)
fmt.Printf("Host: %s Port: %s\n", host, port)
fmt.Printf("User: %s \t", mainURL.User.Username())
p, _ := mainURL.User.Password()
fmt.Printf("Password: %s", p)
}
$ go run main.go
Scheme: https
User: username:password
Host: example.com:8080
Path: /url-parsing-in-GO
Fragment: section
Query: go=best
Host: example.com Port: 8080
User: username Password: password
0
Subscribe to my newsletter
Read articles from Priyansh Sao directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
