swift.go 2.0 KB

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