s3.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package s3
  2. import (
  3. "fmt"
  4. http "net/http"
  5. "github.com/aws/aws-sdk-go/aws"
  6. "github.com/aws/aws-sdk-go/aws/awserr"
  7. "github.com/aws/aws-sdk-go/aws/session"
  8. "github.com/aws/aws-sdk-go/service/s3"
  9. "github.com/imgproxy/imgproxy/v3/config"
  10. )
  11. // transport implements RoundTripper for the 's3' protocol.
  12. type transport struct {
  13. svc *s3.S3
  14. }
  15. func New() (http.RoundTripper, error) {
  16. s3Conf := aws.NewConfig()
  17. if len(config.S3Region) != 0 {
  18. s3Conf.Region = aws.String(config.S3Region)
  19. }
  20. if len(config.S3Endpoint) != 0 {
  21. s3Conf.Endpoint = aws.String(config.S3Endpoint)
  22. s3Conf.S3ForcePathStyle = aws.Bool(true)
  23. }
  24. sess, err := session.NewSession()
  25. if err != nil {
  26. return nil, fmt.Errorf("Can't create S3 session: %s", err)
  27. }
  28. if sess.Config.Region == nil || len(*sess.Config.Region) == 0 {
  29. sess.Config.Region = aws.String("us-west-1")
  30. }
  31. return transport{s3.New(sess, s3Conf)}, nil
  32. }
  33. func (t transport) RoundTrip(req *http.Request) (resp *http.Response, err error) {
  34. input := &s3.GetObjectInput{
  35. Bucket: aws.String(req.URL.Host),
  36. Key: aws.String(req.URL.Path),
  37. }
  38. if len(req.URL.RawQuery) > 0 {
  39. input.VersionId = aws.String(req.URL.RawQuery)
  40. }
  41. if config.ETagEnabled {
  42. if ifNoneMatch := req.Header.Get("If-None-Match"); len(ifNoneMatch) > 0 {
  43. input.IfNoneMatch = aws.String(ifNoneMatch)
  44. }
  45. }
  46. s3req, _ := t.svc.GetObjectRequest(input)
  47. if err := s3req.Send(); err != nil {
  48. if s3err, ok := err.(awserr.RequestFailure); !ok || s3err.StatusCode() != http.StatusNotModified {
  49. return nil, err
  50. }
  51. }
  52. return s3req.HTTPResponse, nil
  53. }