1
0
mirror of https://github.com/imgproxy/imgproxy.git synced 2025-01-08 10:45:04 +02:00
imgproxy/gcs_transport.go

67 lines
1.3 KiB
Go
Raw Normal View History

2018-10-30 14:12:56 +02:00
package main
import (
"context"
2020-02-27 17:44:59 +02:00
"fmt"
2018-10-30 14:12:56 +02:00
"net/http"
"strconv"
2018-10-30 14:12:56 +02:00
"strings"
"cloud.google.com/go/storage"
"google.golang.org/api/option"
)
type gcsTransport struct {
client *storage.Client
}
2020-02-27 17:44:59 +02:00
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())
}
2018-10-30 14:12:56 +02:00
if err != nil {
2020-02-27 17:44:59 +02:00
return nil, fmt.Errorf("Can't create GCS client: %s", err)
2018-10-30 14:12:56 +02:00
}
2020-02-27 17:44:59 +02:00
return gcsTransport{client}, nil
2018-10-30 14:12:56 +02:00
}
func (t gcsTransport) RoundTrip(req *http.Request) (*http.Response, error) {
2018-10-30 14:12:56 +02:00
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)
}
2018-10-30 14:12:56 +02:00
reader, err := obj.NewReader(context.Background())
if err != nil {
return nil, err
}
header := make(http.Header)
header.Set("Cache-Control", reader.Attrs.CacheControl)
2018-10-30 14:12:56 +02:00
return &http.Response{
Status: "200 OK",
StatusCode: 200,
Proto: "HTTP/1.0",
ProtoMajor: 1,
ProtoMinor: 0,
Header: header,
ContentLength: reader.Attrs.Size,
2018-10-30 14:12:56 +02:00
Body: reader,
Close: true,
Request: req,
}, nil
}