chore: add aria2 rpc package

This commit is contained in:
Noah Hsu
2022-06-15 17:15:22 +08:00
parent c65a9b3001
commit 2cddd3cf2b
13 changed files with 1723 additions and 5 deletions

42
pkg/aria2/rpc/proc.go Normal file
View File

@ -0,0 +1,42 @@
package rpc
import "sync"
type ResponseProcFn func(resp clientResponse) error
type ResponseProcessor struct {
cbs map[uint64]ResponseProcFn
mu *sync.RWMutex
}
func NewResponseProcessor() *ResponseProcessor {
return &ResponseProcessor{
make(map[uint64]ResponseProcFn),
&sync.RWMutex{},
}
}
func (r *ResponseProcessor) Add(id uint64, fn ResponseProcFn) {
r.mu.Lock()
r.cbs[id] = fn
r.mu.Unlock()
}
func (r *ResponseProcessor) remove(id uint64) {
r.mu.Lock()
delete(r.cbs, id)
r.mu.Unlock()
}
// Process called by recv routine
func (r *ResponseProcessor) Process(resp clientResponse) error {
id := *resp.Id
r.mu.RLock()
fn, ok := r.cbs[id]
r.mu.RUnlock()
if ok && fn != nil {
defer r.remove(id)
return fn(resp)
}
return nil
}