proxyrotator.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package proxyrotator // import "miniflux.app/v2/internal/proxyrotator"
  4. import (
  5. "net/url"
  6. "sync"
  7. )
  8. var ProxyRotatorInstance *ProxyRotator
  9. // ProxyRotator manages a list of proxies and rotates through them.
  10. type ProxyRotator struct {
  11. proxies []*url.URL
  12. currentIndex int
  13. mutex sync.Mutex
  14. }
  15. // NewProxyRotator creates a new ProxyRotator with the given proxy URLs.
  16. func NewProxyRotator(proxyURLs []string) (*ProxyRotator, error) {
  17. parsedProxies := make([]*url.URL, 0, len(proxyURLs))
  18. for _, p := range proxyURLs {
  19. proxyURL, err := url.Parse(p)
  20. if err != nil {
  21. return nil, err
  22. }
  23. parsedProxies = append(parsedProxies, proxyURL)
  24. }
  25. return &ProxyRotator{
  26. proxies: parsedProxies,
  27. currentIndex: 0,
  28. mutex: sync.Mutex{},
  29. }, nil
  30. }
  31. // GetNextProxy returns the next proxy in the rotation.
  32. func (pr *ProxyRotator) GetNextProxy() *url.URL {
  33. pr.mutex.Lock()
  34. defer pr.mutex.Unlock()
  35. if len(pr.proxies) == 0 {
  36. return nil
  37. }
  38. proxy := pr.proxies[pr.currentIndex]
  39. pr.currentIndex = (pr.currentIndex + 1) % len(pr.proxies)
  40. return proxy
  41. }
  42. // HasProxies checks if there are any proxies available in the rotator.
  43. func (pr *ProxyRotator) HasProxies() bool {
  44. pr.mutex.Lock()
  45. defer pr.mutex.Unlock()
  46. return len(pr.proxies) > 0
  47. }