Welcome To Golang By Example

Parse a URL and extract all the parts in Go (Golang)

Table of Contents

Overview

net/url package of golang contains a Parse function that can be used to parse a given and return the url instance of the URL struct

https://golang.org/pkg/net/url/#URL

Once the given URL is parsed correctly, then it will return the URI object. We can then access the below information from the URI

Let’s see a working program for the same:

We will parse the below URL

https://test:abcd123@golangbyexample.com:8000/tutorials/intro?type=advance&compact=false#history

Then

Program

package main

import (
	"fmt"
	"log"
	"net/url"
)

func main() {
	input_url := "https://test:abcd123@golangbyexample.com:8000/tutorials/intro?type=advance&compact=false#history"
	u, err := url.Parse(input_url)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(u.Scheme)
	fmt.Println(u.User)
	fmt.Println(u.Hostname())
	fmt.Println(u.Port())
	fmt.Println(u.Path)
	fmt.Println(u.RawQuery)
	fmt.Println(u.Fragment)
	fmt.Println(u.String())
}

Output

https
test:abcd123
golangbyexample.com
8000
/tutorials/intro
type=advance&compact=false
history
https://test:abcd123@golangbyexample.com:8000/tutorials/intro?type=advance&compact=false#history

It correctly dumps all the information as seen from the output