swift.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package swift
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "strings"
  9. "time"
  10. "github.com/ncw/swift/v2"
  11. "github.com/imgproxy/imgproxy/v3/config"
  12. )
  13. type transport struct {
  14. con *swift.Connection
  15. }
  16. func New() (http.RoundTripper, error) {
  17. c := &swift.Connection{
  18. UserName: config.SwiftUsername,
  19. ApiKey: config.SwiftAPIKey,
  20. AuthUrl: config.SwiftAuthURL,
  21. AuthVersion: config.SwiftAuthVersion,
  22. Domain: config.SwiftDomain, // v3 auth only
  23. Tenant: config.SwiftTenant, // v2 auth only
  24. Timeout: time.Duration(config.SwiftTimeoutSeconds) * time.Second,
  25. ConnectTimeout: time.Duration(config.SwiftConnectTimeoutSeconds) * time.Second,
  26. }
  27. ctx := context.Background()
  28. err := c.Authenticate(ctx)
  29. if err != nil {
  30. return nil, fmt.Errorf("swift authentication error: %s", err)
  31. }
  32. return transport{con: c}, nil
  33. }
  34. func (t transport) RoundTrip(req *http.Request) (resp *http.Response, err error) {
  35. // Users should have converted the object storage URL in the format of swift://{container}/{object}
  36. container := req.URL.Host
  37. objectName := strings.TrimPrefix(req.URL.Path, "/")
  38. object, objectHeaders, err := t.con.ObjectOpen(req.Context(), container, objectName, false, make(swift.Headers))
  39. header := make(http.Header)
  40. if err != nil {
  41. if errors.Is(err, swift.ObjectNotFound) || errors.Is(err, swift.ContainerNotFound) {
  42. return &http.Response{
  43. StatusCode: http.StatusNotFound,
  44. Proto: "HTTP/1.0",
  45. ProtoMajor: 1,
  46. ProtoMinor: 0,
  47. Header: header,
  48. Body: io.NopCloser(strings.NewReader(err.Error())),
  49. Close: false,
  50. Request: req,
  51. }, nil
  52. }
  53. return nil, fmt.Errorf("error opening object: %v", err)
  54. }
  55. if config.ETagEnabled {
  56. if etag, ok := objectHeaders["Etag"]; ok {
  57. header.Set("ETag", etag)
  58. if len(etag) > 0 && etag == req.Header.Get("If-None-Match") {
  59. object.Close()
  60. return &http.Response{
  61. StatusCode: http.StatusNotModified,
  62. Proto: "HTTP/1.0",
  63. ProtoMajor: 1,
  64. ProtoMinor: 0,
  65. Header: header,
  66. ContentLength: 0,
  67. Body: nil,
  68. Close: false,
  69. Request: req,
  70. }, nil
  71. }
  72. }
  73. }
  74. for k, v := range objectHeaders {
  75. header.Set(k, v)
  76. }
  77. return &http.Response{
  78. Status: "200 OK",
  79. StatusCode: 200,
  80. Proto: "HTTP/1.0",
  81. ProtoMajor: 1,
  82. ProtoMinor: 0,
  83. Header: header,
  84. Body: object,
  85. Close: true,
  86. Request: req,
  87. }, nil
  88. }