s3.go 1.4 KB

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