aria2g

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 24, 2026 License: MIT Imports: 16 Imported by: 0

README

aria2g

aria2g is a concurrent-safe Go client for aria2c's JSON-RPC API over HTTP and WebSocket.

go get github.com/depthbomb/aria2g
client, err := aria2g.New("http://localhost:6800", "rpc-secret")
if err != nil {
	log.Fatal(err)
}

gid, err := client.AddURI(context.Background(), []string{
	"https://example.com/archive.zip",
}, aria2g.Options{
	"dir":                       "downloads",
	"max-connection-per-server": "8",
	"header":                    []string{"Accept-Language: en", "Cache-Control: no-cache"},
}, nil)

Start aria2 with RPC enabled:

aria2c --enable-rpc --rpc-listen-port=6800 --rpc-secret=rpc-secret

Every operation accepts a context.Context, and clients may be shared by concurrent goroutines. Authentication tokens are inserted automatically only where aria2 permits them, including inside batch and system.multicall calls.

API coverage

The typed API covers every aria2 1.37.0 RPC method:

  • URI, torrent, and Metalink submission
  • graceful and forced pause, resume, removal, and shutdown
  • active, waiting, stopped, and individual download status
  • files, URIs, peers, HTTP/FTP servers, and piece completion
  • queue positions and source URI changes
  • per-download and global options, global statistics, session information, and result cleanup
  • system.multicall, system.listMethods, and system.listNotifications

Client.Call remains available for extensions or newer daemon methods. aria2's numeric download fields remain strings, avoiding overflow or precision loss. Pass nil or an empty slice to status methods to omit the optional key filter and request every field.

Options accepts string values and the documented []string form used by repeatable header and index-out options.

Batching

Batch uses native JSON-RPC batching, preserves call order even if the server reorders responses, and reports failures per call:

results, err := client.Batch(ctx, []aria2g.MethodCall{
	{Method: "getVersion"},
	{Method: "getGlobalStat"},
})
if err != nil {
	log.Fatal(err)
}

var version aria2g.Version
if err := results[0].Decode(&version); err != nil {
	log.Fatal(err)
}

MultiCall is also available when compatibility with system.multicall is required.

WebSocket notifications

WebSocket clients expose the same typed methods and native batching, plus aria2's six server notifications:

client, err := aria2g.DialWebSocket(ctx, "http://localhost:6800", "rpc-secret")
if err != nil {
	log.Fatal(err)
}
defer client.Close()

for notification := range client.Notifications() {
	event, err := notification.DecodeEvent()
	if err != nil {
		continue
	}
	log.Printf("%s: %s", notification.Method, event.GID)
}

The endpoint scheme is converted automatically (http to ws, https to wss). Notification buffering is bounded to 64 events by default. Applications should continuously drain Notifications; if the buffer fills, the connection closes with ErrNotificationOverflow instead of silently losing events or growing memory without bound. Set Config.NotificationBuffer to tune the bound.

Errors and limits

aria2 failures are returned as *aria2g.RPCError. Non-success HTTP statuses are *aria2g.HTTPError. Responses are limited to 16 MiB by default; configure MaxResponseBytes, request Timeout, TLS settings, or a custom HTTP client with NewWithConfig / DialWebSocketWithConfig. Individual calls can always be canceled through their context.

Performance

aria2g is a thin JSON-RPC client. End-to-end RPC latency and download throughput are normally dominated by aria2c, the network, and the requested workload. Native Batch can reduce transport round trips when independent calls can be grouped.

A pre-1.0 profiling pass found and removed reflection-heavy MultiCall payloads, redundant native-batch response storage, a redundant WebSocket JSON decode, and an extra authenticated-parameter copy. The following client-only microbenchmark results compare the implementations before and after those changes:

Benchmark Before After Improvement
Authenticated request construction 215.8 ns, 200 B, 6 allocs 144.4 ns, 152 B, 4 allocs 33% faster, 24% fewer bytes
MultiCall request build and marshal, 1,000 calls 1.643 ms, 838 KiB, 17,010 allocs 1.094 ms, 361 KiB, 8,006 allocs 33% faster, 57% fewer bytes
Native batch response ordering, 1,000 calls 76.69 us, 176 KiB 51.58 us, 68.1 KiB 33% faster, 61% fewer bytes
WebSocket response routing 2.041 us, 184 B, 4 allocs 1.112 us, 168 B, 3 allocs 45% faster, 25% fewer allocs

These are medians from eight samples per revision on Go 1.27.0, Windows/amd64, an Intel Core i7-9700K, and GOMAXPROCS=8. Benchstat reported p < 0.001 for each timing improvement. The benchmarks deliberately exclude socket and daemon work, so the absolute values are revision-comparison data, not a latency SLA. Loopback transport results were not published because they measured the mock server and Windows networking more than the library and were too variable to support a performance claim.

Run the maintained benchmarks locally with:

$env:ARIA2G_SKIP_LIVE = '1'
go test -run '^$' -bench . -benchmem -benchtime=750ms -count=8 .

For meaningful comparisons, use the same machine, power state, and Go toolchain for both revisions, then compare their raw output with benchstat.

Examples

Runnable programs for client setup, downloads, batching, concurrency, and WebSocket notifications are available in the examples directory.

Testing

When aria2c is installed, go test ./... automatically starts an isolated loopback daemon with a temporary directory and exercises both HTTP and WebSocket RPC paths. Set ARIA2G_ENDPOINT (and optionally ARIA2G_SECRET) to run those compatibility tests against an existing daemon instead. If aria2c is unavailable, the live tests are skipped and the in-process protocol tests still run. Set ARIA2G_SKIP_LIVE=1 to run only the in-process tests even when aria2c is installed.

Documentation

Overview

Package aria2g provides a client for aria2's JSON-RPC API over HTTP and WebSocket.

Index

Examples

Constants

View Source
const (
	// DefaultEndpoint is the aria2 JSON-RPC endpoint used when Config.Endpoint
	// is empty.
	DefaultEndpoint = "http://localhost:6800/jsonrpc"
	// DefaultMaxResponseBytes is the default maximum size of one RPC response.
	DefaultMaxResponseBytes = int64(16 << 20)
	// DefaultNotificationBuffer is the default number of WebSocket
	// notifications that may wait for the application.
	DefaultNotificationBuffer = 64
)
View Source
const (
	// NotificationDownloadStart is emitted when a download starts.
	NotificationDownloadStart = "aria2.onDownloadStart"
	// NotificationDownloadPause is emitted when a download is paused.
	NotificationDownloadPause = "aria2.onDownloadPause"
	// NotificationDownloadStop is emitted when a download is stopped by the user.
	NotificationDownloadStop = "aria2.onDownloadStop"
	// NotificationDownloadComplete is emitted when a download completes.
	NotificationDownloadComplete = "aria2.onDownloadComplete"
	// NotificationDownloadError is emitted when a download stops because of an error.
	NotificationDownloadError = "aria2.onDownloadError"
	// NotificationBTDownloadComplete is emitted when a BitTorrent download completes and seeding begins.
	NotificationBTDownloadComplete = "aria2.onBtDownloadComplete"
)

Variables

View Source
var (
	// ErrResponseTooLarge indicates that an RPC response exceeded the configured MaxResponseBytes limit.
	ErrResponseTooLarge = errors.New("aria2g: response exceeds configured size limit")
	// ErrClientClosed indicates that an operation used a closed WebSocket client.
	ErrClientClosed = errors.New("aria2g: WebSocket client is closed")
	// ErrNotificationOverflow indicates that an application did not consume WebSocket notifications quickly enough.
	// The client is closed when this occurs so that notifications are never silently dropped.
	ErrNotificationOverflow = errors.New("aria2g: WebSocket notification buffer is full")
)

Functions

This section is empty.

Types

type BatchResult

type BatchResult struct {
	// Result contains the raw successful result for decoding with Decode.
	Result json.RawMessage
	// Error contains the per-call RPC failure, if any.
	Error *RPCError
}

BatchResult is one result from Batch. Exactly one of Result and Error is set.

func (BatchResult) Decode

func (r BatchResult) Decode(dst any) error

Decode unmarshals a successful batch result into dst, which must be a non-nil pointer. If the call failed, Decode returns its RPCError.

type Bitfield

type Bitfield struct {
	Bitfield        string `json:"bitfield"`
	CompletedLength string `json:"completedLength"`
	TotalLength     string `json:"totalLength"`
}

Bitfield contains piece-completion information for a download.

type Bittorrent

type Bittorrent struct {
	AnnounceList [][]string     `json:"announceList"`
	Comment      string         `json:"comment"`
	CreationDate int64          `json:"creationDate"`
	Mode         string         `json:"mode"`
	Info         BittorrentInfo `json:"info"`
}

Bittorrent contains BitTorrent-specific download metadata.

type BittorrentInfo

type BittorrentInfo struct {
	Name string `json:"name"`
}

BittorrentInfo contains metadata from a torrent's info dictionary.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client communicates with one aria2 RPC server. It is safe for concurrent use. A Client created by DialWebSocket or DialWebSocketWithConfig must be closed when no longer needed.

func DialWebSocket

func DialWebSocket(ctx context.Context, endpoint, secret string) (*Client, error)

DialWebSocket connects using aria2's WebSocket JSON-RPC transport. The returned Client supports all typed methods and delivers server notifications through Notifications.

Example
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/depthbomb/aria2g"
)

func main() {
	ctx := context.Background()
	client, err := aria2g.DialWebSocket(ctx, "http://localhost:6800", "rpc-secret")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	for notification := range client.Notifications() {
		event, err := notification.DecodeEvent()
		if err != nil {
			log.Printf("invalid notification: %v", err)
			continue
		}
		fmt.Printf("%s: %s\n", notification.Method, event.GID)
	}
}

func DialWebSocketWithConfig

func DialWebSocketWithConfig(ctx context.Context, cfg Config) (*Client, error)

DialWebSocketWithConfig connects using aria2's WebSocket JSON-RPC transport and the supplied configuration. The caller must close the returned Client.

func New

func New(endpoint, secret string) (*Client, error)

New creates an HTTP client. endpoint may be a full JSON-RPC URL or an aria2 base URL.

Example
package main

import (
	"fmt"
	"log"

	"github.com/depthbomb/aria2g"
)

func main() {
	client, err := aria2g.New("", "")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(client.Endpoint())
}
Output:
http://localhost:6800/jsonrpc

func NewWithConfig

func NewWithConfig(cfg Config) (*Client, error)

NewWithConfig creates an HTTP client using cfg. An empty endpoint selects DefaultEndpoint.

Example
package main

import (
	"fmt"
	"log"
	"time"

	"github.com/depthbomb/aria2g"
)

func main() {
	client, err := aria2g.NewWithConfig(aria2g.Config{
		Endpoint:         "https://downloads.example.com/aria2",
		Secret:           "rpc-secret",
		Timeout:          30 * time.Second,
		MaxResponseBytes: 4 << 20,
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(client.Endpoint())
}
Output:
https://downloads.example.com/aria2/jsonrpc
func (c *Client) AddMetalink(ctx context.Context, metalink string, options Options, position *int) ([]string, error)

AddMetalink adds a base64-encoded Metalink document and returns its download GIDs. position is nil to append the resulting downloads to the queue.

func (*Client) AddTorrent

func (c *Client) AddTorrent(ctx context.Context, torrent string, uris []string, options Options, position *int) (string, error)

AddTorrent adds a base64-encoded torrent file and returns its GID. uris optionally provides web-seed URIs; position is nil to append to the queue.

func (*Client) AddURI

func (c *Client) AddURI(ctx context.Context, uris []string, options Options, position *int) (string, error)

AddURI adds a download from one or more source URIs and returns its GID. position is optional; nil appends the download to aria2's queue.

Example
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/depthbomb/aria2g"
)

func main() {
	client, err := aria2g.New("http://localhost:6800", "rpc-secret")
	if err != nil {
		log.Fatal(err)
	}

	gid, err := client.AddURI(context.Background(), []string{
		"https://example.com/archive.zip",
	}, aria2g.Options{
		"dir":                       "downloads",
		"max-connection-per-server": "8",
	}, nil)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(gid)
}

func (*Client) Batch

func (c *Client) Batch(ctx context.Context, calls []MethodCall) ([]BatchResult, error)

Batch sends native JSON-RPC batch requests in one HTTP request or WebSocket message. Results are returned in call order even if the server reorders them. Per-call RPC failures are stored in BatchResult.Error.

Example
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/depthbomb/aria2g"
)

func main() {
	client, err := aria2g.New("http://localhost:6800", "rpc-secret")
	if err != nil {
		log.Fatal(err)
	}

	results, err := client.Batch(context.Background(), []aria2g.MethodCall{
		{Method: "getVersion"},
		{Method: "getGlobalStat"},
	})
	if err != nil {
		log.Fatal(err)
	}

	var version aria2g.Version
	if err := results[0].Decode(&version); err != nil {
		log.Fatal(err)
	}
	fmt.Println(version.Version)
}

func (*Client) Call

func (c *Client) Call(ctx context.Context, method string, result any, params ...any) error

Call invokes a fully-qualified aria2 method (for example, "aria2.tellActive"). Unqualified names are prefixed with "aria2.". result must be a non-nil pointer. The secret token is inserted automatically.

Example
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/depthbomb/aria2g"
)

func main() {
	client, err := aria2g.New("http://localhost:6800", "rpc-secret")
	if err != nil {
		log.Fatal(err)
	}

	// Call provides access to RPC methods that do not yet have a typed wrapper.
	var methods []string
	if err := client.Call(context.Background(), "system.listMethods", &methods); err != nil {
		log.Fatal(err)
	}
	fmt.Println(methods)
}

func (*Client) ChangeGlobalOption

func (c *Client) ChangeGlobalOption(ctx context.Context, options Options) error

ChangeGlobalOption updates aria2's changeable global options.

func (*Client) ChangeOption

func (c *Client) ChangeOption(ctx context.Context, gid string, options Options) error

ChangeOption changes options for a download while it is active or waiting.

func (*Client) ChangePosition

func (c *Client) ChangePosition(ctx context.Context, gid string, pos int, how PositionMode) (int, error)

ChangePosition moves a queued download and returns its new zero-based position. how must be one of aria2's position modes: POS_SET, POS_CUR, or POS_END.

func (*Client) ChangeURI

func (c *Client) ChangeURI(ctx context.Context, gid string, fileIndex int, del, add []string, position *int) ([2]int, error)

ChangeURI removes and adds source URIs for a file. It returns removed and added counts. position is nil to use aria2's default insertion position.

func (*Client) Close

func (c *Client) Close() error

Close closes a WebSocket client. It is a no-op for an HTTP client.

func (*Client) Endpoint

func (c *Client) Endpoint() string

Endpoint returns the JSON-RPC endpoint.

func (*Client) ForcePause

func (c *Client) ForcePause(ctx context.Context, gid string) (string, error)

ForcePause immediately pauses a download and returns its GID.

func (*Client) ForcePauseAll

func (c *Client) ForcePauseAll(ctx context.Context) error

ForcePauseAll immediately pauses every active download.

func (*Client) ForceRemove

func (c *Client) ForceRemove(ctx context.Context, gid string) (string, error)

ForceRemove immediately removes a download and returns its GID.

func (*Client) ForceShutdown

func (c *Client) ForceShutdown(ctx context.Context) error

ForceShutdown immediately stops aria2, interrupting active downloads.

func (*Client) GetFiles

func (c *Client) GetFiles(ctx context.Context, gid string) ([]File, error)

GetFiles returns file metadata and source URIs for a download.

func (*Client) GetGlobalOption

func (c *Client) GetGlobalOption(ctx context.Context) (Options, error)

GetGlobalOption returns aria2's global options.

func (*Client) GetGlobalStat

func (c *Client) GetGlobalStat(ctx context.Context) (GlobalStat, error)

GetGlobalStat returns aggregate transfer speeds and download counts.

func (*Client) GetOption

func (c *Client) GetOption(ctx context.Context, gid string) (Options, error)

GetOption returns the options currently applied to a download.

func (*Client) GetPeers

func (c *Client) GetPeers(ctx context.Context, gid string) ([]Peer, error)

GetPeers returns connected BitTorrent peers for a download.

func (*Client) GetPieceStat

func (c *Client) GetPieceStat(ctx context.Context, gid string) (Bitfield, error)

GetPieceStat returns piece-completion information using tellStatus. aria2 has no getPieceStat RPC method; this is a convenience operation retained for callers that only need the three piece-related fields.

func (*Client) GetServers

func (c *Client) GetServers(ctx context.Context, gid string) ([]Server, error)

GetServers returns per-file HTTP/FTP server information for a download.

func (*Client) GetSessionInfo

func (c *Client) GetSessionInfo(ctx context.Context) (SessionInfo, error)

GetSessionInfo returns the current aria2 session identifier.

func (*Client) GetURIs

func (c *Client) GetURIs(ctx context.Context, gid string, fileIndex int) ([]URI, error)

GetURIs returns the source URIs for the one-based fileIndex in a download.

func (*Client) GetVersion

func (c *Client) GetVersion(ctx context.Context) (Version, error)

GetVersion returns the aria2 version and enabled features.

func (*Client) ListMethods

func (c *Client) ListMethods(ctx context.Context) ([]string, error)

ListMethods returns the RPC methods advertised by aria2.

func (*Client) ListNotifications

func (c *Client) ListNotifications(ctx context.Context) ([]string, error)

ListNotifications returns the notifications emitted by aria2.

func (*Client) MultiCall

func (c *Client) MultiCall(ctx context.Context, calls []MethodCall) ([]json.RawMessage, error)

MultiCall invokes several methods through system.multicall in one request. Successful slots retain system.multicall's one-element array wrapper; sub-call errors are represented by aria2's fault object in their slot. Batch is usually more convenient because it separates per-call errors.

func (*Client) Notifications

func (c *Client) Notifications() <-chan Notification

Notifications returns the notification stream for a WebSocket client. It returns nil for an HTTP client. The channel closes when the client closes.

func (*Client) Pause

func (c *Client) Pause(ctx context.Context, gid string) (string, error)

Pause pauses a download and returns its GID.

func (*Client) PauseAll

func (c *Client) PauseAll(ctx context.Context) error

PauseAll pauses every active download.

func (*Client) PurgeDownloadResult

func (c *Client) PurgeDownloadResult(ctx context.Context) error

PurgeDownloadResult removes all completed and errored download results.

func (*Client) Remove

func (c *Client) Remove(ctx context.Context, gid string) (string, error)

Remove removes a download gracefully and returns its GID.

func (*Client) RemoveDownloadResult

func (c *Client) RemoveDownloadResult(ctx context.Context, gid string) (string, error)

RemoveDownloadResult removes one completed or errored result and returns its GID.

func (*Client) SaveSession

func (c *Client) SaveSession(ctx context.Context) error

SaveSession writes the current session to aria2's configured session file.

func (*Client) Shutdown

func (c *Client) Shutdown(ctx context.Context) error

Shutdown requests a graceful aria2 shutdown after active downloads stop.

func (*Client) TellActive

func (c *Client) TellActive(ctx context.Context, keys []string) ([]Download, error)

TellActive returns every active download. keys limits returned status fields.

func (*Client) TellStatus

func (c *Client) TellStatus(ctx context.Context, gid string, keys []string) (Download, error)

TellStatus returns status for gid. Pass nil or an empty keys slice for all fields.

func (*Client) TellStopped

func (c *Client) TellStopped(ctx context.Context, offset, num int, keys []string) ([]Download, error)

TellStopped returns up to num stopped downloads beginning at offset. keys limits fields.

func (*Client) TellWaiting

func (c *Client) TellWaiting(ctx context.Context, offset, num int, keys []string) ([]Download, error)

TellWaiting returns up to num queued downloads beginning at offset. keys limits fields.

func (*Client) Unpause

func (c *Client) Unpause(ctx context.Context, gid string) (string, error)

Unpause resumes a paused download and returns its GID.

func (*Client) UnpauseAll

func (c *Client) UnpauseAll(ctx context.Context) error

UnpauseAll resumes every paused download.

type Config

type Config struct {
	// Endpoint is an aria2 base URL or full JSON-RPC URL. An empty value uses DefaultEndpoint. HTTP constructors accept
	// http and https URLs; WebSocket constructors also accept ws and wss and convert HTTP schemes automatically.
	Endpoint string
	// Secret is aria2's RPC secret without the "token:" prefix. An empty value disables token authentication.
	Secret string
	// HTTPClient supplies the transport used for HTTP requests and WebSocket handshakes. A shallow copy is made before
	// applying other Config fields. Nil uses http.DefaultClient.
	HTTPClient *http.Client
	// Timeout replaces HTTPClient.Timeout when nonzero. Per-call contexts can impose shorter deadlines. A negative
	// value is invalid.
	Timeout time.Duration
	// TLSConfig configures TLS for HTTPS and WSS endpoints. It is cloned before use and requires HTTPClient.Transport
	// to be nil or an *http.Transport.
	TLSConfig *tls.Config
	// MaxResponseBytes limits a single HTTP or WebSocket response. Zero uses DefaultMaxResponseBytes; a negative value
	// is invalid.
	MaxResponseBytes int64
	// NotificationBuffer bounds notifications waiting for the application. If it fills, the WebSocket connection closes
	// with ErrNotificationOverflow rather than dropping events or growing memory without bound. Zero uses
	// DefaultNotificationBuffer.
	NotificationBuffer int
}

Config controls a Client. HTTPClient is copied before Timeout is applied, so constructors never mutate a caller-owned client. A zero Timeout leaves the HTTP client's timeout unchanged. MaxResponseBytes defaults to 16 MiB.

type Download

type Download struct {
	GID                    string      `json:"gid"`
	Status                 string      `json:"status"`
	TotalLength            string      `json:"totalLength"`
	CompletedLength        string      `json:"completedLength"`
	UploadLength           string      `json:"uploadLength"`
	Bitfield               string      `json:"bitfield"`
	DownloadSpeed          string      `json:"downloadSpeed"`
	UploadSpeed            string      `json:"uploadSpeed"`
	InfoHash               string      `json:"infoHash"`
	NumSeeders             string      `json:"numSeeders"`
	Seeder                 string      `json:"seeder"`
	PieceLength            string      `json:"pieceLength"`
	NumPieces              string      `json:"numPieces"`
	Connections            string      `json:"connections"`
	ErrorCode              string      `json:"errorCode"`
	ErrorMessage           string      `json:"errorMessage"`
	FollowedBy             []string    `json:"followedBy"`
	Following              string      `json:"following"`
	BelongsTo              string      `json:"belongsTo"`
	Dir                    string      `json:"dir"`
	Files                  []File      `json:"files"`
	Bittorrent             *Bittorrent `json:"bittorrent,omitempty"`
	VerifiedLength         string      `json:"verifiedLength"`
	VerifyIntegrityPending string      `json:"verifyIntegrityPending"`
}

Download is a download status as returned by tellActive/tellWaiting/tellStopped.

type Event

type Event struct {
	GID string `json:"gid"`
}

Event identifies the download associated with an aria2 notification.

type File

type File struct {
	Index           string `json:"index"`
	Path            string `json:"path"`
	Length          string `json:"length"`
	CompletedLength string `json:"completedLength"`
	Selected        string `json:"selected"`
	URIs            []URI  `json:"uris"`
}

File describes one file in a download and its source URIs.

type GlobalStat

type GlobalStat struct {
	DownloadSpeed   string `json:"downloadSpeed"`
	UploadSpeed     string `json:"uploadSpeed"`
	NumActive       string `json:"numActive"`
	NumWaiting      string `json:"numWaiting"`
	NumStopped      string `json:"numStopped"`
	NumStoppedTotal string `json:"numStoppedTotal"`
}

GlobalStat contains aria2's aggregate transfer speeds and download counts.

type HTTPError

type HTTPError struct {
	// StatusCode is the HTTP response status code.
	StatusCode int
	// Status is the complete HTTP response status, such as "503 Service Unavailable".
	Status string
	// Body contains the size-limited, whitespace-trimmed response body.
	Body string
}

HTTPError reports a non-2xx response from the RPC endpoint.

func (*HTTPError) Error

func (e *HTTPError) Error() string

type MethodCall

type MethodCall struct {
	// Method is a fully-qualified RPC method or an unqualified aria2 method.
	Method string
	// Params contains method parameters without the authentication token.
	Params []any
}

MethodCall is one request for Batch or MultiCall. Params do not include the authentication token; it is added automatically to aria2.* methods.

type Notification

type Notification struct {
	Method string          `json:"method"`
	Params json.RawMessage `json:"params"`
}

Notification is an aria2 server-initiated WebSocket notification. Params is the raw JSON array supplied by aria2. DecodeEvent decodes its standard event.

func (Notification) DecodeEvent

func (n Notification) DecodeEvent() (Event, error)

DecodeEvent decodes the single download event in n.Params.

Example
package main

import (
	"encoding/json"
	"fmt"
	"log"

	"github.com/depthbomb/aria2g"
)

func main() {
	n := aria2g.Notification{
		Method: aria2g.NotificationDownloadComplete,
		Params: json.RawMessage(`[{"gid":"2089b05ecca3d829"}]`),
	}
	event, err := n.DecodeEvent()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(event.GID)
}
Output:
2089b05ecca3d829

type Options

type Options map[string]any

Options are aria2 option key/value pairs. Values are normally strings. The header and index-out options may also be []string, as defined by aria2's RPC protocol.

type Peer

type Peer struct {
	PeerID        string `json:"peerId"`
	IP            string `json:"ip"`
	Port          string `json:"port"`
	Bitfield      string `json:"bitfield"`
	AmChoking     string `json:"amChoking"`
	PeerChoking   string `json:"peerChoking"`
	DownloadSpeed string `json:"downloadSpeed"`
	UploadSpeed   string `json:"uploadSpeed"`
	Seeder        string `json:"seeder"`
}

Peer describes a connected BitTorrent peer.

type PositionMode

type PositionMode string

PositionMode controls how ChangePosition interprets its pos argument.

const (
	// PositionSet moves a download to the absolute zero-based position pos.
	PositionSet PositionMode = "POS_SET"
	// PositionCurrent moves a download by pos positions relative to its current position.
	PositionCurrent PositionMode = "POS_CUR"
	// PositionEnd moves a download by pos positions relative to the end of the queue.
	PositionEnd PositionMode = "POS_END"
)

type RPCError

type RPCError struct {
	// Code is aria2's JSON-RPC error code.
	Code int `json:"code"`
	// Message describes the RPC failure.
	Message string `json:"message"`
	// Data contains optional structured details supplied by aria2.
	Data json.RawMessage `json:"data,omitempty"`
}

RPCError is an error returned by aria2.

func (*RPCError) Error

func (e *RPCError) Error() string

type Server

type Server struct {
	Index   string       `json:"index"`
	Servers []ServerInfo `json:"servers"`
}

Server groups the HTTP or FTP servers used for one file in a download.

type ServerInfo

type ServerInfo struct {
	URI           string `json:"uri"`
	CurrentURI    string `json:"currentUri"`
	DownloadSpeed string `json:"downloadSpeed"`
}

ServerInfo describes one HTTP or FTP source and its current transfer speed.

type SessionInfo

type SessionInfo struct {
	SessionID string `json:"sessionId"`
}

SessionInfo identifies the running aria2 session.

type URI

type URI struct {
	URI    string `json:"uri"`
	Status string `json:"status"`
}

URI describes a source URI and its health state.

type Version

type Version struct {
	Version         string   `json:"version"`
	EnabledFeatures []string `json:"enabledFeatures"`
}

Version describes the running aria2 version and its enabled features.

Directories

Path Synopsis
examples
add-download command
Program add-download submits a URI and follows it until it stops.
Program add-download submits a URI and follows it until it stops.
batch command
Program batch combines independent JSON-RPC calls into one request.
Program batch combines independent JSON-RPC calls into one request.
concurrent-status command
Program concurrent-status fetches several download statuses concurrently.
Program concurrent-status fetches several download statuses concurrently.
version command
Program version prints information about the aria2c daemon.
Program version prints information about the aria2c daemon.
websocket command
Program websocket prints aria2 download events until interrupted.
Program websocket prints aria2 download events until interrupted.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL