Hugo v0.112.0 - Additional media types with resources.GetRemote

The resources.GetRemote template function is, by design, limited to downloading a predefined list of media types[1] that are common and safe (e.g., image/jpeg, text/css, application/json, etc.).

In some projects, you might need to access a remote file that is not in the predefined list of common and safe media types. If you try, Hugo will throw an error such as:

ERROR 2023/05/24 14:22:33 error calling resources.GetRemote: failed to resolve media type for remote resource https://example.org/foo.ext

Hugo v0.112.0 introduced a new security setting which allows you to add one or more media types to the predefined list. For example, to allow resources.GetRemote to get .docx (Microsoft Word) documents:

[security.http]
mediaTypes = ['^application/vnd.openxmlformats-officedocument.wordprocessingml.document$']

Then in your template you can do something like:

{{ $url := "https://example.org/test.docx" }}
{{ $name := path.Base $url }}
{{ with resources.GetRemote $url }}
  {{ with .Err }}
    {{ errorf "%s" . }}
  {{ else }}
    {{ with resources.Copy $name . }}
      <a href="{{ .RelPermalink }}" download>{{ $name }}</a>
    {{ end }}
  {{ end }}
{{ else }}
  {{ errorf "Unable to get remote resource %q" $url }}
{{ end }}

Instead of adding the media types to your site configuration, you can also set an environment variable. For example:

HUGO_SECURITY_HTTP_MEDIATYPES="^image/avif$"

  1. Formerly known as MIME types ↩ī¸Ž

4 Likes