Start learning free

LESSON 2 OF 173 · BACKEND: HOW THE WEB WORKS

The Parts of a URL in Go

Practice

A URL is the full address of something on the web. It is made of parts, and each part answers its own question: the scheme (how to talk to the server), the host (which computer), the port (which server on that computer), the path (what you want) and the query string (with which options, after the ?).

The function url.Parse, from the net/url package, splits a URL into those parts. Some are fields, like .Path, and some are methods, like .Hostname(). Here it is on another URL:

site, _ := url.Parse("https://algocademy.com/blog?page=2")
fmt.Println(site.Hostname())   // algocademy.com
fmt.Println(site.Port())       // empty: no port is written
fmt.Println(site.RawQuery)     // page=2

Scheme, host and port tell your program where to send the request. The path and the query travel inside the request and tell the server what you want. When a URL writes no port, the client uses 80 for http and 443 for https.

The starting code splits the address of the supplier's cheap products with url.Parse, keeps the result in parts and prints the whole URL. Your finished program must print:

URL: http://127.0.0.1:8001/prices?max_price=5
Scheme: http
Host: 127.0.0.1
Port: 8001
Path: /prices
Query: max_price=5

Your task: below the "URL:" print, print the scheme, host, port, path and query of parts, each after its label.


Assignment
Follow the Coding Tutorial to print each of the five parts of the supplier's URL.


Hint
The scheme, path and query are fields: .Scheme, .Path and .RawQuery. The host and port come from methods, with (): .Hostname() and .Port(). The field .Host would keep the port too.


STEP 1 OF 5
    Ctrl + Enter to check

    Web Url Parts in Go

    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free