This repository was archived by the owner on Jul 10, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp.go
More file actions
110 lines (79 loc) · 1.74 KB
/
http.go
File metadata and controls
110 lines (79 loc) · 1.74 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
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
package reader
import (
"context"
"fmt"
"github.com/whosonfirst/go-ioutil"
wof_reader "github.com/whosonfirst/go-reader"
"io"
_ "log"
"net/http"
"net/url"
"path/filepath"
"time"
)
type HTTPReader struct {
wof_reader.Reader
url *url.URL
throttle <-chan time.Time
user_agent string
}
func init() {
ctx := context.Background()
schemes := []string{
"http",
"https",
}
for _, s := range schemes {
err := wof_reader.RegisterReader(ctx, s, NewHTTPReader)
if err != nil {
panic(err)
}
}
}
func NewHTTPReader(ctx context.Context, uri string) (wof_reader.Reader, error) {
u, err := url.Parse(uri)
if err != nil {
return nil, err
}
rate := time.Second / 3
throttle := time.Tick(rate)
r := HTTPReader{
throttle: throttle,
url: u,
}
q := u.Query()
ua := q.Get("user-agent")
if ua != "" {
r.user_agent = ua
}
return &r, nil
}
func (r *HTTPReader) Read(ctx context.Context, uri string) (io.ReadSeekCloser, error) {
<-r.throttle
u, _ := url.Parse(r.url.String())
u.Path = filepath.Join(u.Path, uri)
url := u.String()
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, fmt.Errorf("Failed to create new request, %w", err)
}
if r.user_agent != "" {
req.Header.Set("User-Agent", r.user_agent)
}
cl := &http.Client{}
rsp, err := cl.Do(req)
if err != nil {
return nil, fmt.Errorf("Failed to execute request, %w", err)
}
if rsp.StatusCode != 200 {
return nil, fmt.Errorf("Unexpected status code: %s", rsp.Status)
}
fh, err := ioutil.NewReadSeekCloser(rsp.Body)
if err != nil {
return nil, fmt.Errorf("Failed to create new ReadSeekCloser, %w", err)
}
return fh, nil
}
func (r *HTTPReader) ReaderURI(ctx context.Context, uri string) string {
return uri
}