proxyrotator.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. if len(pr.proxies) == 0 {
  34. return nil
  35. }
  36. pr.mutex.Lock()
  37. proxy := pr.proxies[pr.currentIndex]
  38. pr.currentIndex = (pr.currentIndex + 1) % len(pr.proxies)
  39. pr.mutex.Unlock()
  40. return proxy
  41. }
  42. // HasProxies checks if there are any proxies available in the rotator.
  43. func (pr *ProxyRotator) HasProxies() bool {
  44. return len(pr.proxies) > 0
  45. }