How to modify public location of cached remote resources?

I’m currently writing a new shortcode. In that shortcode I am getting some JSON from an API. In that JSON response are URLs of remote images. I want to include those images in my rendered page, but I don’t want to hotlink the images. I want to download the images and serve them myself. That helps to ensure my site always has the images, even if the remote site goes down. It also helps protects the privacy of visitors to my site.

This is actually working. My code looks like this. I removed all the error checking from this example so it’s easier to understand. Just trust me that I am doing appropriate error checking on every GetRemote call just like in the documentation.

{{ $api_url := printf "https://api.example.com/%v/?format=json" (.Get "id") }}
{{ $json_response := resources.GetRemote $api_url }}
{{ $json_data := $json_response | transform.Unmarshal }}
{{ $image_url := $json_data.image_url }}
{{ $image := resources.GetRemote $image_url }}
<img src="{{ $image.RelPermalink }}" />
...

This code works. The image is downloaded into the cache directory. The image is included in the final rendered page appropriately. There is just one problem.

When the images are included into the public directory, they are included at the top level.

% ls -1 public
2896259253.jpg
404.html
6315214750.jpg
8914314963.jpg
9907551409.jpg
blog
css
favicon.ico
index.html
index.xml
sitemap.xml

This is not great! I don’t want the images to be served from the top of the URL structure like this:

https://mydomain.com/8914314963.jpg

I want them to be put somewhere that makes sense like this:

https://mydomain/com/images/remote/8914314963.jpg

What do I have to configure to move them to a more appropriate location inside of public? Thanks.

Never mind. I figured it out.

If anyone comes along and finds this, the answer is to use resources.Copy to manually move the resource to an appropriate location. The cleanest way I found to do this is to construct the path with a printf and then pipe the GetRemote to resources.Copy.

Example:

{{ $json_data := $json_response | transform.Unmarshal }}
{{ $image_url := $json_data.image_url }}
{{ $image_path := printf "/images/%v.jpg" $json_data.image_name }}
{{ $image := resources.GetRemote $image_url | resources.Copy $image_path }}
<img src="{{ $image.RelPermalink }}" />

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.