From 5927d8aca8df26bf770ca061cdd3e00794847b27 Mon Sep 17 00:00:00 2001 From: Will Hawkins Date: Fri, 10 Dec 2021 01:20:50 -0500 Subject: Initial commit. --- mc/mc.go | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 mc/mc.go (limited to 'mc/mc.go') diff --git a/mc/mc.go b/mc/mc.go new file mode 100644 index 0000000..4d405de --- /dev/null +++ b/mc/mc.go @@ -0,0 +1,60 @@ +package mc + +import ( + "context" + "fmt" + "io" + "io/ioutil" + "net/http" +) + +type MeasurableConnection interface { + Start(context.Context) bool + Stop() bool + Downloaded() uint64 +} + +type LoadBearingConnection struct { + Path string + ctx context.Context + cancel context.CancelFunc + downloaded uint64 + client *http.Client +} + +func (lbc *LoadBearingConnection) Downloaded() uint64 { + return lbc.downloaded +} + +func (lbc *LoadBearingConnection) Start(ctx context.Context) bool { + fmt.Printf("Starting a LBC ...") + lbc.ctx, lbc.cancel = context.WithCancel(ctx) + lbc.downloaded = 0 + lbc.client = &http.Client{} + get, err := lbc.client.Get(lbc.Path) + + if err != nil { + return false + } + go doDownload(get, &lbc.downloaded, lbc.ctx) + return true +} + +func (lbc *LoadBearingConnection) Stop() bool { + lbc.cancel() + return true +} + +func doDownload(get *http.Response, count *uint64, ctx context.Context) { + for ctx.Err() == nil { + n, err := io.CopyN(ioutil.Discard, get.Body, 1024*1024) + if err != nil { + fmt.Printf("Done reading!\n") + break + } + fmt.Printf("Read some bytes: %d\n", n) + *count += uint64(n) + } + fmt.Printf("Cancelling my download.\n") + get.Body.Close() +} -- cgit v1.2.3