Parsing string URLs

Good day everyone!

I’m looking at creating a shortcode that will create an img + photo credit. Something like this:
{{< img-credit “https://en.wikipedia.org/wiki/Winter_Is_Coming#/media/File:Game_of_Thrones_S01-E01_Eddard_Stark.jpg” >}}

would produce something like this:


Photo credit: en.wikipedia.org

Now, that would require parsing of URL string and use the hostname portion. I’ve found the go language has a struct named url that we can use: https://gobyexample.com/url-parsing

I’d see something like:
{{ $u, $err := url.Parse(“http://url.com”) }}
{{ $u.Host }}

My question is, can we use go functions like this one inside a shortcode / template? If not, what solution would you use?

Thanks!

No you cannot. You may be able to do it with the builtin string template funcs. Not sure.

Check out the replaceRE template function.

1 Like

@sleclerc That image is coming up as a broken link. Can you write out your desired result, please?

It did work! Thanks a lot :slight_smile:

I just changed the original message. Thanks for pointing it!

Try this code snippet:

{{ $url := "https://discuss.gohugo.io/t/parsing-string-urls/4100" }}
{{ $url := replace $url "https://" "" }}
{{ $url := replace $url "http://" "" }}
{{ $url := split $url "/" }}

{{ if ge (len $url) 1 }}
    {{ index $url 0 }}
{{ end }}

It outputs discuss.gohugo.io. However, it doesn’t remove port numbers like in this url:

example.com:8080/path/to/image.png

But this case should be rare.

3 Likes

Thanks ! I’ll test both solutions.