Handling URLs in Golang

Glitch
2 min readMar 27, 2023

--

Handling URLs in Golang can be a crucial part of developing web applications. URLs are the primary way of accessing resources on the internet, and they need to be managed efficiently to ensure the smooth functioning of web applications. In this blog, we will explore how to handle URLs in Golang.

What is a URL?

A URL (Uniform Resource Locator) is a string of characters that identifies a resource on the internet. A typical URL has three main parts:

Protocol - specifies the protocol to be used to access the resource (e.g., HTTP, HTTPS, FTP, etc.).
Hostname - identifies the server where the resource is located (e.g., www.example.com).
Path - specifies the location of the resource on the server (e.g., /images/picture.jpg).
URLs can also contain other components such as query parameters, fragments, and usernames and passwords.

How to handle URLs in Golang

Golang provides a powerful built-in package called "net/url" to handle URLs. This package provides a URL type, which can be used to parse and manipulate URLs.

Parsing a URL

To parse a URL in Golang, we use the Parse function of the net/url package. The Parse function takes a string representation of a URL as input and returns a URL type.

package main

import (
"fmt"
"net/url"
)

func main() {
u, err := url.Parse("https://www.example.com/path/to/resource?param1=value1&param2=value2#fragment")
if err != nil {
panic(err)
}

fmt.Println("Protocol:", u.Scheme)
fmt.Println("Hostname:", u.Hostname())
fmt.Println("Path:", u.Path)
fmt.Println("Query:", u.RawQuery)
fmt.Println("Fragment:", u.Fragment)
}
The output of this program will be:

Protocol: https
Hostname: www.example.com
Path: /path/to/resource
Query: param1=value1&param2=value2
Fragment: fragment
Modifying a URL

The URL type in Golang is immutable, which means that we cannot modify it directly. To modify a URL, we need to create a new URL type based on the existing URL.

package main

import (
"fmt"
"net/url"
)

func main() {
u, err := url.Parse("https://www.example.com/path/to/resource?param1=value1&param2=value2#fragment")
if err != nil {
panic(err)
}

// Modify the protocol
u.Scheme = "http"

// Modify the hostname
u.Host = "localhost:8080"

// Modify the path
u.Path = "/new/path"

// Add a new query parameter
q := u.Query()
q.Set("param3", "value3")
u.RawQuery = q.Encode()

fmt.Println(u.String())
}
The output of this program will be:

http://localhost:8080/new/path?param1=value1&param2=value2&param3=value3#fragment

--

--

No responses yet