Skip to content

Instantly share code, notes, and snippets.

@wgfm
Created October 18, 2023 12:57
Show Gist options
  • Save wgfm/2fbbc9ac1c7de3a101b966c533b43dc1 to your computer and use it in GitHub Desktop.
Save wgfm/2fbbc9ac1c7de3a101b966c533b43dc1 to your computer and use it in GitHub Desktop.
Ardan exercise
package main
import (
"fmt"
"net/http"
"sync"
"time"
)
func downloadSize(startDate, endDate time.Time) (int64, error) {
const base = "https://d37ci6vzurychx.cloudfront.net/trip-data/%s_tripdata_%d-%d.parquet"
sizeCh := make(chan int64)
var wg sync.WaitGroup
for _, colour := range []string{"yellow", "green"} {
for date := startDate; !date.After(endDate); date = addMonth(date, 1) {
wg.Add(1)
go func(date time.Time, colour string) {
url := fmt.Sprintf(base, colour, date.Year(), date.Month())
req, err := http.NewRequest("HEAD", url, nil)
if err != nil {
panic(err)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
sizeCh <- resp.ContentLength
wg.Done()
}(date, colour)
}
}
var totalSize int64
go func() {
for size := range sizeCh {
totalSize += size
}
}()
wg.Wait()
close(sizeCh)
return totalSize, nil
}
func addMonth(t time.Time, m int) time.Time {
x := t.AddDate(0, m, 0)
if d := x.Day(); d != t.Day() {
return x.AddDate(0, 0, -d)
}
return x
}
func main() {
now := time.Now()
yesteryear := now.AddDate(-1, 0, 0)
size, err := downloadSize(yesteryear, now)
if err != nil {
panic(err)
}
fmt.Println(size)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment