Get File Size of ZIP URL

I’m migrating my website from Wordpress to Hugo and want to show the file size of ZIP files on the download page. The ZIP files themselves are hosted on GitHub.

For example, I want to print Download: tinylog-2.5.0.zip (1.49 MB) for the URL “https://github.com/tinylog-org/tinylog/releases/download/2.5.0/tinylog-2.5.0.zip”.

Unfortunately, (os.Stat "tinylog-2.5.0.zip").Size works only for local files, but not for URLs like (os.Stat "https://github.com/tinylog-org/tinylog/releases/download/2.5.0/tinylog-2.5.0.zip").Size.

Is there any way to get the file size directly from the GitHub URL?

Use the resources.GetRemote method to query the GitHub REST API.

You could do this with a shortcode…

layouts/shortcodes/github-asset-download.html
{{- /* Set defaults. */}}
{{- $owner := "" }}
{{- $repo := "" }}
{{- $tag := "" }}
{{- $assetName := "" }}

{{- /* Get params. */}}
{{- with .Get "owner" }}
  {{- $owner = . }}
{{- end }}
{{- with .Get "repo" }}
  {{- $repo = . }}
{{- end }}
{{- with .Get "tag" }}
  {{- $tag = . | string }}
{{- end }}
{{- with .Get "assetName" }}
  {{- $assetName = . }}
{{- end }}

{{- /* Validate params. */}}
{{- if not $owner }}
  {{- errorf "The %q shortcode requires a %q parameter. See %s" .Name "owner" .Position }}
{{- end }}
{{- if not $repo }}
  {{- errorf "The %q shortcode requires a %q parameter. See %s" .Name "repo" .Position }}
{{- end }}
{{- if not $tag }}
  {{- errorf "The %q shortcode requires a %q parameter. See %s" .Name "tag" .Position }}
{{- end }}
{{- if not $assetName }}
  {{- errorf "The %q shortcode requires a %q parameter. See %s" .Name "assetName" .Position }}
{{- end }}

{{- $url := printf "https://api.github.com/repos/%s/%s/releases/tags/%s" $owner $repo $tag }}
{{- with resources.GetRemote $url }}
  {{- with .Err }}
    {{- errorf "%s" . }}
  {{- else }}
    {{- with .Content | transform.Unmarshal }}
      {{- with where .assets "name" $assetName }}
        {{- with index . 0 }}
          {{- $size := printf "%.2f MB" (div .size 1048576) -}}
          <a href="{{- .browser_download_url }}">{{ .name }}</a> ({{ $size }})
        {{- end }}
      {{- else }}
        {{- errorf "Unable to find asset with name %q" $assetName }}
      {{- end }}
    {{- end }}
  {{- end }}
{{- else }}
  {{- errorf "Unable to obtain remote resource %s" $url }}
{{- end -}}


markdown

{{< github-asset-download
  owner="tinylog-org"
  repo="tinylog"
  tag="2.5.0"
  assetName="tinylog-2.5.0.zip"
>}}

rendered as

<a href="https://github.com/tinylog-org/tinylog/releases/download/2.5.0/tinylog-2.5.0.zip">tinylog-2.5.0.zip</a> (1.49 MB)
6 Likes

Thank you very much for your complete and elegant solution! Using the GitHub API is indeed a smart and clean solution.

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