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

90 lines
1.8 KiB
Go
Raw Normal View History

2021-04-26 13:52:50 +02:00
package gcs
2018-10-30 14:12:56 +02:00
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"
2021-09-30 16:23:30 +02:00
"github.com/imgproxy/imgproxy/v3/config"
2018-10-30 14:12:56 +02:00
"google.golang.org/api/option"
)
2021-04-26 13:52:50 +02:00
type transport struct {
2018-10-30 14:12:56 +02:00
client *storage.Client
}
2021-04-26 13:52:50 +02:00
func New() (http.RoundTripper, error) {
var (
client *storage.Client
err error
)
2021-04-26 13:52:50 +02:00
if len(config.GCSKey) > 0 {
client, err = storage.NewClient(context.Background(), option.WithCredentialsJSON([]byte(config.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
}
2021-04-26 13:52:50 +02:00
return transport{client}, nil
2018-10-30 14:12:56 +02:00
}
2021-04-26 13:52:50 +02:00
func (t transport) 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)
}
2021-09-29 12:23:54 +02:00
header := make(http.Header)
2018-10-30 14:12:56 +02:00
2021-09-29 12:23:54 +02:00
if config.ETagEnabled {
attrs, err := obj.Attrs(context.Background())
if err != nil {
return nil, err
}
header.Set("ETag", attrs.Etag)
if attrs.Etag == req.Header.Get("If-None-Match") {
return &http.Response{
StatusCode: http.StatusNotModified,
Proto: "HTTP/1.0",
ProtoMajor: 1,
ProtoMinor: 0,
Header: header,
ContentLength: 0,
Body: nil,
Close: false,
Request: req,
}, nil
}
}
reader, err := obj.NewReader(context.Background())
2018-10-30 14:12:56 +02:00
if err != nil {
return nil, err
}
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
}