-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
89 lines (77 loc) · 2.13 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
package main
import (
"fmt"
"log/slog"
"os"
"strconv"
"strings"
"flag"
"github.com/alipourhabibi/http-downloader/http"
)
var logLevel = flag.String("level", "error", "level is used to set the logging level")
var addSource = flag.Bool("source", false, "is used by logger to log the caller function or not")
var ip = flag.String("ip", "127.0.0.1", "destination ip of the server")
var port = flag.Int("port", 80, "destination port of the server")
var fileName = flag.String("filename", "", "file name which is going to be downloaded from server")
var levelMap = map[string]slog.Level{
"DEBUG": slog.LevelDebug,
"INFO": slog.LevelInfo,
"WARN": slog.LevelWarn,
"ERROR": slog.LevelError,
}
func main() {
flag.Parse()
level := levelMap[strings.ToUpper(*logLevel)]
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
AddSource: *addSource,
Level: level,
}))
slog.SetDefault(logger)
if *fileName == "" {
slog.Error("filename", "error", "filename can't be empty")
return
}
server, err := http.NewServer(*ip, *port, 8000)
var msg string
msg = fmt.Sprintf("GET /%s HTTP/1.1\r\nHOST:localhost\r\nRange: bytes=\r\n\r\n", *fileName)
err = server.SendMsg(msg)
_, response, err := server.RecieveMsg()
if err != nil {
slog.Error("RecieveMsg", "error", err.Error())
return
}
status := http.GetStatus(response)
if status == 404 {
slog.Error("404 Not Found")
return
}
if status >= 500 {
slog.Error("Internal Server Error")
return
}
header, err := http.GetHeader(response)
if err != nil {
slog.Error("GetHeader", "error", err.Error())
return
}
size := header["Content-Length"]
intSize, err := strconv.Atoi(size)
if err != nil {
slog.Error("strconv error", "error", err.Error())
return
}
slog.Debug("Content-Length", "size", intSize)
server, err = http.NewServer(*ip, *port, 8000)
if intSize <= 1000 {
err = server.DownloadOne(*fileName, intSize)
if err != nil {
panic(err)
}
} else {
if header["Accept-Ranges"] != "" && strings.HasPrefix(header["Accept-Ranges"], "bytes") {
server.DownloadParallel(*fileName, intSize)
} else {
server.DownloadOne(*fileName, intSize)
}
}
}