-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
185 lines (144 loc) · 3.66 KB
/
main.go
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
package main
import (
"errors"
"fmt"
"io/ioutil"
"net/http"
"os"
"strconv"
"sync"
"time"
)
type Download struct {
Url string // Url de la descarga
TargetPath string // Ruta de destino
TotalSections int // Número de secciones en las que se dividirá la descarga (conexiones simultáneas al servidor)
}
func main() {
startTime := time.Now() // Tiempo de inicio de la descarga
d := Download{
Url: "https://www.dropbox.com/s/urmuwd87rlg5sdd/RESUMEN%20OCTAVOS%20DE%20FINAL%20MUNDIAL%20QATAR%202022.mp4?dl=1",
TargetPath: "final.mp4",
TotalSections: 10,
}
err := d.Do()
if err != nil {
fmt.Println(err)
}
fmt.Printf("Descarga finalizada en %v seconds\n", time.Now().Sub(startTime).Seconds())
}
func (d Download) Do() error {
fmt.Println("Conectando con el servidor...")
r, err := d.getNewRequest("HEAD")
if err != nil {
return err
}
resp, err := http.DefaultClient.Do(r)
if err != nil {
return err
}
if resp.StatusCode > 299 {
return errors.New(fmt.Sprintf("No se puede procesar la solicitud, la respuesta es: %v", resp.StatusCode))
}
size, err := strconv.Atoi(resp.Header.Get("Content-Length"))
if (err != nil) || (size == 0) {
return fmt.Errorf("No se puede obtener el tamaño del archivo")
} else {
fmt.Printf("Tamaño del archivo: %v bytes\n", size)
}
var sections = make([][2]int, d.TotalSections)
sectionSize := size / d.TotalSections
for i := range sections {
if i == 0 {
sections[i][0] = 0
} else {
sections[i][0] = sections[i-1][1] + 1
}
if i < d.TotalSections-1 {
sections[i][1] = sections[i][0] + sectionSize
} else {
sections[i][1] = size - 1
}
}
fmt.Println(sections)
var wg sync.WaitGroup
for i, s := range sections {
wg.Add(1)
// Se crea una copia de las variables i y s para que no se sobreescriban
i := i
s := s
go func() {
defer wg.Done()
err := d.downloadSection(i, s)
if err != nil {
panic(err)
}
}()
}
wg.Wait()
err = d.mergeSections(sections)
if err != nil {
return err
}
return nil
}
func (d Download) getNewRequest(method string) (*http.Request, error) {
req, err := http.NewRequest(
method,
d.Url,
nil,
)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", "Silly Downloader Manager v001")
return req, nil
}
func (d Download) downloadSection(i int, s [2]int) error {
r, err := d.getNewRequest("GET")
if err != nil {
return err
}
r.Header.Set("Range", fmt.Sprintf("bytes=%v-%v", s[0], s[1]))
resp, err := http.DefaultClient.Do(r)
if err != nil {
return err
}
fmt.Printf("Descargado %v bytes de la sección %v: %v\n", resp.Header.Get("Content-Length"), i, s)
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
e := ioutil.WriteFile(fmt.Sprintf("section-%v.tmp", i), b, os.ModePerm)
if e != nil {
return err
}
return nil
}
func (d Download) mergeSections(sections [][2]int) error {
f, err := os.OpenFile(d.TargetPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, os.ModePerm)
if err != nil {
return err
}
defer f.Close()
for i := range sections {
b, err := ioutil.ReadFile(fmt.Sprintf("section-%v.tmp", i))
if err != nil {
return err
}
n, err := f.Write(b)
if err != nil {
return err
}
fmt.Printf("Escritos %v bytes en el archivo final\n", n)
}
// d.clean()
return nil
}
// El código es bastante simple, lo que hace es dividir el archivo en secciones y descargar cada una de ellas en un hilo diferente. Una vez que todas las secciones han sido descargadas, se unen en un archivo final.
// Funcion para limpiar todos los archivos temporales
func (d Download) clean() {
for i := 0; i < d.TotalSections; i++ {
os.Remove(fmt.Sprintf("section-%v.tmp", i))
}
}