Get file size from url

Hey i want to get file size from url
i try to use that

out, err := exec.Command("curl", "-sI", url, "|", "grep", "-i", "Content-Length", "|", "cut", "-c17-").Output();

With url = http://speedtest-sgp1.digitalocean.com/5gb.test
But i get a error code 6
Why?

Because curl doesn’t understand what you mean by | and everything after that.

There is no shell involved.

Okey but how I can get file size from url in go in this case?

I would use Go’s HTTP client to make the HEAD request:

httpClient := &http.Client{Timeout: 5 * time.Second}
resp, err := httpClient.Head(url)

if err != nil {
  log.Fatalf("error on HEAD request: %s", err.Error())
}

fmt.Printf("Content-Length: %d \n", resp.ContentLength)

If you must use cURL, you can either make the cURL request and parse the output yourself in Go:

curlOut, err := exec.Command("curl", "-sI", url).Output()

if err != nil {
  log.Fatalf("error on CURL: %s", err.Error())
}

// This output is a list of response headers that you can parse yourself
fmt.Println(string(curlOut))

or invoke a shell so that you can use your cut command:

curlOut, err := exec.Command(
  "/bin/bash",
  "-c",
  fmt.Sprintf("curl -sI %s | grep -i content-length | cut -c17-", url)).Output()

if err != nil {
  log.Fatalf("error on CURL: %s", err.Error())
}

fmt.Printf("Content-Length: %s", curlOut)

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