azuret.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package azure
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "net/url"
  7. "strings"
  8. "github.com/Azure/azure-storage-blob-go/azblob"
  9. "github.com/imgproxy/imgproxy/v3/config"
  10. )
  11. type transport struct {
  12. serviceURL *azblob.ServiceURL
  13. }
  14. func New() (http.RoundTripper, error) {
  15. credential, err := azblob.NewSharedKeyCredential(config.ABSName, config.ABSKey)
  16. if err != nil {
  17. return nil, err
  18. }
  19. pipeline := azblob.NewPipeline(credential, azblob.PipelineOptions{})
  20. endpoint := config.ABSEndpoint
  21. if len(endpoint) == 0 {
  22. endpoint = fmt.Sprintf("https://%s.blob.core.windows.net", config.ABSName)
  23. }
  24. endpointURL, err := url.Parse(endpoint)
  25. if err != nil {
  26. return nil, err
  27. }
  28. serviceURL := azblob.NewServiceURL(*endpointURL, pipeline)
  29. return transport{&serviceURL}, nil
  30. }
  31. func (t transport) RoundTrip(req *http.Request) (resp *http.Response, err error) {
  32. containerURL := t.serviceURL.NewContainerURL(strings.ToLower(req.URL.Host))
  33. blobURL := containerURL.NewBlockBlobURL(strings.TrimPrefix(req.URL.Path, "/"))
  34. get, err := blobURL.Download(context.Background(), 0, azblob.CountToEnd, azblob.BlobAccessConditions{}, false, azblob.ClientProvidedKeyOptions{})
  35. if err != nil {
  36. return nil, err
  37. }
  38. if config.ETagEnabled {
  39. etag := string(get.ETag())
  40. if etag == req.Header.Get("If-None-Match") {
  41. if body := get.Response().Body; body != nil {
  42. get.Response().Body.Close()
  43. }
  44. return &http.Response{
  45. StatusCode: http.StatusNotModified,
  46. Proto: "HTTP/1.0",
  47. ProtoMajor: 1,
  48. ProtoMinor: 0,
  49. Header: make(http.Header),
  50. ContentLength: 0,
  51. Body: nil,
  52. Close: false,
  53. Request: req,
  54. }, nil
  55. }
  56. }
  57. return get.Response(), nil
  58. }