Parsing URL in Hugo Framework

March 22, 2024 (7mo ago)

I was working on a feature that requires a comprehensive analysis of all the components within a URL, including but not limited to the protocol, domain, path, query parameters, and fragments.

To accomplish this task effectively, I have utilized the urls.Parse function, which allows me to parse and extract specific components such as the scheme, host, path, query parameters, and fragment from a given URL. This method ensures accurate and detailed analysis of the URL structure, enabling me to implement the necessary functionalities.

The Code

We’ll start with this code:

{{ $url := "https://isaacdarcilla.com/blog/parsing-url-in-hugo-framework#the-code" }}
{{ $url = urls.Parse $url }}

The urls.Parse function returns a URL struct, so the value of each struct field would be:

{{ $url.Scheme }}    // https                               
{{ $url.Host }}      // isaacdarcilla.com                         
{{ $url.Path }}      // /blog/parsing-url-in-hugo-framework/    
{{ $url.Fragment }}  // the-code