swift.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package swift
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "strings"
  7. "time"
  8. "github.com/ncw/swift/v2"
  9. "github.com/imgproxy/imgproxy/v3/config"
  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. object, objectHeaders, err := t.con.ObjectOpen(req.Context(), container, objectName, false, make(swift.Headers))
  37. if err != nil {
  38. return nil, fmt.Errorf("error opening object: %v", err)
  39. }
  40. header := make(http.Header)
  41. if config.ETagEnabled {
  42. if etag, ok := objectHeaders["Etag"]; ok {
  43. header.Set("ETag", etag)
  44. if len(etag) > 0 && etag == req.Header.Get("If-None-Match") {
  45. object.Close()
  46. return &http.Response{
  47. StatusCode: http.StatusNotModified,
  48. Proto: "HTTP/1.0",
  49. ProtoMajor: 1,
  50. ProtoMinor: 0,
  51. Header: header,
  52. ContentLength: 0,
  53. Body: nil,
  54. Close: false,
  55. Request: req,
  56. }, nil
  57. }
  58. }
  59. }
  60. for k, v := range objectHeaders {
  61. header.Set(k, v)
  62. }
  63. return &http.Response{
  64. Status: "200 OK",
  65. StatusCode: 200,
  66. Proto: "HTTP/1.0",
  67. ProtoMajor: 1,
  68. ProtoMinor: 0,
  69. Header: header,
  70. Body: object,
  71. Close: true,
  72. Request: req,
  73. }, nil
  74. }