1
0
mirror of https://github.com/imgproxy/imgproxy.git synced 2025-02-07 11:36:25 +02:00

85 lines
1.9 KiB
Go
Raw Normal View History

2021-04-26 17:52:50 +06:00
package s3
2018-05-26 16:22:41 +02:00
import (
2020-02-27 21:44:59 +06:00
"fmt"
2022-03-17 20:43:25 +06:00
"io"
http "net/http"
2022-03-17 20:43:25 +06:00
"strings"
2018-05-26 16:22:41 +02:00
"github.com/aws/aws-sdk-go/aws"
2021-12-16 01:27:07 +06:00
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
2018-05-26 16:22:41 +02:00
"github.com/aws/aws-sdk-go/service/s3"
2021-04-26 17:52:50 +06:00
2021-09-30 20:23:30 +06:00
"github.com/imgproxy/imgproxy/v3/config"
2018-05-26 16:22:41 +02:00
)
2021-04-26 17:52:50 +06:00
// transport implements RoundTripper for the 's3' protocol.
type transport struct {
2018-05-26 16:22:41 +02:00
svc *s3.S3
}
2021-04-26 17:52:50 +06:00
func New() (http.RoundTripper, error) {
2018-11-13 19:23:59 +06:00
s3Conf := aws.NewConfig()
2021-04-26 17:52:50 +06:00
if len(config.S3Region) != 0 {
s3Conf.Region = aws.String(config.S3Region)
2018-11-13 19:23:59 +06:00
}
2021-04-26 17:52:50 +06:00
if len(config.S3Endpoint) != 0 {
s3Conf.Endpoint = aws.String(config.S3Endpoint)
s3Conf.S3ForcePathStyle = aws.Bool(true)
2018-11-13 19:23:59 +06:00
}
sess, err := session.NewSession()
if err != nil {
2020-02-27 21:44:59 +06:00
return nil, fmt.Errorf("Can't create S3 session: %s", err)
}
2018-12-09 18:11:15 +06:00
if sess.Config.Region == nil || len(*sess.Config.Region) == 0 {
sess.Config.Region = aws.String("us-west-1")
}
2021-04-26 17:52:50 +06:00
return transport{s3.New(sess, s3Conf)}, nil
2018-05-26 16:22:41 +02:00
}
2021-04-26 17:52:50 +06:00
func (t transport) RoundTrip(req *http.Request) (resp *http.Response, err error) {
2018-05-26 16:22:41 +02:00
input := &s3.GetObjectInput{
Bucket: aws.String(req.URL.Host),
Key: aws.String(req.URL.Path),
}
if len(req.URL.RawQuery) > 0 {
input.VersionId = aws.String(req.URL.RawQuery)
}
2021-09-29 16:23:54 +06:00
if config.ETagEnabled {
if ifNoneMatch := req.Header.Get("If-None-Match"); len(ifNoneMatch) > 0 {
input.IfNoneMatch = aws.String(ifNoneMatch)
}
}
2018-05-26 16:22:41 +02:00
s3req, _ := t.svc.GetObjectRequest(input)
2019-03-22 22:57:18 +06:00
if err := s3req.Send(); err != nil {
2022-03-17 20:43:25 +06:00
if s3err, ok := err.(awserr.RequestFailure); !ok || s3err.StatusCode() < 100 || s3err.StatusCode() == 301 {
2021-12-16 01:27:07 +06:00
return nil, err
2022-03-17 20:43:25 +06:00
} else {
body := strings.NewReader(s3err.Message())
return &http.Response{
StatusCode: s3err.StatusCode(),
Proto: "HTTP/1.0",
ProtoMajor: 1,
ProtoMinor: 0,
Header: http.Header{},
ContentLength: int64(body.Len()),
Body: io.NopCloser(body),
Close: false,
Request: s3req.HTTPRequest,
}, nil
2021-12-16 01:27:07 +06:00
}
2018-05-26 16:22:41 +02:00
}
2019-03-22 22:57:18 +06:00
return s3req.HTTPResponse, nil
2018-05-26 16:22:41 +02:00
}