DEV Community

Ali Torabi
Ali Torabi

Posted on

Download torrent files using Golang

Hey everyone,

Today, I want to show you how to download torrent files easily using Golang. So stay with me…

First of all, you should have your torrent file or its magnet URL, which you can obtain from torrent websites such as 1377x.to or RARBG, and so on.

In this post, we will be using the ‘github.com/aliworkshop/torrent’ package to download torrent files with suitable downloading progress.

Step 1:
go get -v github.com/aliworkshop/torrent

Step 2:

client := torrent.NewClient(torrent.ClientConfig{
 TickerDuration: 3 * time.Second,
 })
defer client.Stop()
Enter fullscreen mode Exit fullscreen mode

In this code, we create a client to start adding torrent files to.

torrent.NewClient takes a configuration parameter where you can set options. In our example, we only defined TickerDuration, which determines the duration of the downloading progress display.

We use defer to stop the client after all torrents have finished downloading.

Step 3:

err := client.AddTorrent("magnet:?xt=urn:btih:AE204757FE376C70852CD5818B01870F05EE7064")
 if err != nil {
 log.Fatalln("error on add torrent magnet url")
 }

Enter fullscreen mode Exit fullscreen mode

In this code, we added our torrent file’s magnet URL to the client to start the download later.

If you want to download using a torrent file, you can add the relative path instead:

err := client.AddTorrent(“/path/to/file”)
 if err != nil {
 log.Fatalln(“error on add torrent file”)
 }

Enter fullscreen mode Exit fullscreen mode

You can add more torrent files as needed and download them concurrently.

Step 4:

eg, _ := errgroup.WithContext(context.Background())
for _, tt := range client.GetTorrents() {
    eg.Go(func(t torrent.TorrentModel) func() error {
        return func() error {
            t.Initiate()
            t.Download()
            go t.DownloadLog()
            return nil
        }
    }(tt))
}
eg.Wait()

Enter fullscreen mode Exit fullscreen mode

In this code, we start downloading the torrent files concurrently using the errgroup package in Golang. It allows us to perform concurrent jobs and handle errors if any of them occur.

Step 5:

client.GetClient().WaitAll()
 log.Print(“congratulations, all torrents downloaded!”)

Enter fullscreen mode Exit fullscreen mode

Here, we wait for all torrent files to finish downloading before displaying a completion message.

Please note that this code assumes you have imported the necessary packages and have the required dependencies installed.

I hope this helps! Let me know if you have any further questions.

Top comments (0)