forked from imgproxy/imgproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgcs_transport.go
66 lines (53 loc) · 1.33 KB
/
gcs_transport.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
package main
import (
"context"
"fmt"
"net/http"
"strconv"
"strings"
"cloud.google.com/go/storage"
"google.golang.org/api/option"
)
type gcsTransport struct {
client *storage.Client
}
func newGCSTransport() (http.RoundTripper, error) {
var (
client *storage.Client
err error
)
if len(conf.GCSKey) > 0 {
client, err = storage.NewClient(context.Background(), option.WithCredentialsJSON([]byte(conf.GCSKey)))
} else {
client, err = storage.NewClient(context.Background())
}
if err != nil {
return nil, fmt.Errorf("Can't create GCS client: %s", err)
}
return gcsTransport{client}, nil
}
func (t gcsTransport) RoundTrip(req *http.Request) (*http.Response, error) {
bkt := t.client.Bucket(req.URL.Host)
obj := bkt.Object(strings.TrimPrefix(req.URL.Path, "/"))
if g, err := strconv.ParseInt(req.URL.RawQuery, 10, 64); err == nil && g > 0 {
obj = obj.Generation(g)
}
reader, err := obj.NewReader(context.Background())
if err != nil {
return nil, err
}
header := make(http.Header)
header.Set("Cache-Control", reader.Attrs.CacheControl)
return &http.Response{
Status: "200 OK",
StatusCode: 200,
Proto: "HTTP/1.0",
ProtoMajor: 1,
ProtoMinor: 0,
Header: header,
ContentLength: reader.Attrs.Size,
Body: reader,
Close: true,
Request: req,
}, nil
}