blob: 23029767cc6503c4ecfc26d60a614a4a39aa5d5c (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
|
package main
import (
"bytes"
"fmt"
"io"
)
type File struct {
Announce string `bencode:"announce"`
Info FileInfo `bencode:"info"`
}
type FileInfo struct {
Length int `bencode:"length"`
Name string `bencode:"name"`
PieceLength int `bencode:"piece length"`
Pieces string `bencode:"pieces"`
}
func NewFile() *File {
return &File{}
}
func (f *File) ReadFrom(r io.ReadCloser) error {
buf := new(bytes.Buffer)
_, err := buf.ReadFrom(r)
if err != nil {
return err
}
defer func(r io.ReadCloser) {
err := r.Close()
if err != nil {
fmt.Printf("failed to close: %v+\n", err)
}
}(r)
if err != nil {
return err
}
decoded, err := NewDecoder(buf.String()).Decode()
if err != nil {
return err
}
content, ok := decoded.(map[string]any)
if !ok {
return fmt.Errorf("invalid contents")
}
f.Announce, ok = content["announce"].(string)
if !ok {
return fmt.Errorf("invalid announce field")
}
info, ok := content["info"].(map[string]any)
if !ok {
return fmt.Errorf("invalid info field")
}
f.Info.Length, ok = info["length"].(int)
if !ok {
return fmt.Errorf("invalid info.length field")
}
f.Info.Name, ok = info["name"].(string)
if !ok {
return fmt.Errorf("invalid info.name field")
}
f.Info.PieceLength, ok = info["piece length"].(int)
if !ok {
return fmt.Errorf("invalid info.piece length field")
}
f.Info.Pieces, ok = info["pieces"].(string)
if !ok {
return fmt.Errorf("invalid info.pieces field")
}
return nil
}
|