-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetch.go
More file actions
82 lines (69 loc) · 1.76 KB
/
fetch.go
File metadata and controls
82 lines (69 loc) · 1.76 KB
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
package main
import (
"encoding/base64"
"io"
"net/http"
"os"
"strings"
)
func fetch(ctx Context) (*http.Response, bool) {
if ctx.Url.Scheme == "data" {
header, data, found := strings.Cut(ctx.Url.Opaque, ",")
if !found {
return nil, false
}
if !strings.HasPrefix(header, "application/json") {
return nil, false
}
if strings.Contains(header, ";base64") {
decoded, err := base64.StdEncoding.DecodeString(data)
if err != nil {
return nil, false
}
data = string(decoded)
}
return &http.Response{
StatusCode: 200,
Status: "OK",
Body: io.NopCloser(strings.NewReader(data)),
}, true
}
if ctx.Url.Scheme == "file" && ctx.Url.Host == "sourcerer" {
f, err := os.Open(strings.TrimPrefix(ctx.Url.Path, "/"))
if err != nil {
Error(ctx.Depth, "Failed to read file:", err)
return nil, false
}
return &http.Response{
StatusCode: 200,
Status: "OK",
Body: io.NopCloser(f),
}, true
}
if _, cached := ctx.Cache[ctx.Url.String()]; cached {
return nil, false
} else {
ctx.Cache[ctx.Url.String()] = struct{}{}
}
Info(ctx.Depth, "Fetching URL:", ctx.Url.String())
res, err := http.Get(ctx.Url.String())
if err != nil {
res.Body.Close()
Error(ctx.Depth, "Failed to fetch URL:", err)
return nil, false
}
if res.StatusCode < 200 || res.StatusCode >= 300 {
res.Body.Close()
Warn(ctx.Depth, "URL responded with status:", res.Status)
return nil, false
}
// if res.Header.Get("Content-Type") == "" {
// res.Body.Close()
// Warn(ctx.Depth, "URL responded with no content type")
// ext := filepath.Ext(ctx.Url.Path)
// mimeType := mime.TypeByExtension(ext)
// res.Header.Set("Content-Type", mimeType)
// }
Success(ctx.Depth, "URL responded with status:", res.Status)
return res, true
}