forked from stellar/go
/
http_archive.go
82 lines (72 loc) · 1.86 KB
/
http_archive.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
// Copyright 2016 Stellar Development Foundation and contributors. Licensed
// under the Apache License, Version 2.0. See the COPYING file at the root
// of this distribution or at http://www.apache.org/licenses/LICENSE-2.0
package archivist
import (
"errors"
"fmt"
"io"
"net/http"
"net/url"
"path"
)
type HttpArchiveBackend struct {
client http.Client
base url.URL
}
func checkResp(r *http.Response) error {
if r.StatusCode >= 200 && r.StatusCode < 400 {
return nil
} else {
return fmt.Errorf("Bad HTTP response '%s' for GET '%s'",
r.Status, r.Request.URL.String())
}
}
func (b *HttpArchiveBackend) GetFile(pth string) (io.ReadCloser, error) {
var derived url.URL = b.base
derived.Path = path.Join(derived.Path, pth)
resp, err := b.client.Get(derived.String())
if err != nil {
if resp != nil && resp.Body != nil {
resp.Body.Close()
}
return nil, err
}
err = checkResp(resp)
if err != nil {
if resp != nil && resp.Body != nil {
resp.Body.Close()
}
return nil, err
}
return resp.Body, nil
}
func (b *HttpArchiveBackend) Exists(pth string) bool {
var derived url.URL = b.base
derived.Path = path.Join(derived.Path, pth)
resp, err := b.client.Head(derived.String())
if resp != nil && resp.Body != nil {
resp.Body.Close()
}
return err == nil && resp != nil && checkResp(resp) == nil
}
func (b *HttpArchiveBackend) PutFile(pth string, in io.ReadCloser) error {
in.Close()
return errors.New("PutFile not available over HTTP")
}
func (b *HttpArchiveBackend) ListFiles(pth string) (chan string, chan error) {
ch := make(chan string)
er := make(chan error)
close(ch)
er <- errors.New("ListFiles not available over HTTP")
close(er)
return ch, er
}
func (b *HttpArchiveBackend) CanListFiles() bool {
return false
}
func MakeHttpBackend(base *url.URL, opts ConnectOptions) ArchiveBackend {
return &HttpArchiveBackend{
base: *base,
}
}