upstream.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package loadbalance
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "net/http"
  6. "net/url"
  7. "strings"
  8. "imuslab.com/zoraxy/mod/dynamicproxy/dpcore"
  9. )
  10. // StartProxy create and start a HTTP proxy using dpcore
  11. // Example of webProxyEndpoint: https://example.com:443 or http://192.168.1.100:8080
  12. func (u *Upstream) StartProxy() error {
  13. //Filter the tailing slash if any
  14. domain := u.OriginIpOrDomain
  15. if len(domain) == 0 {
  16. return errors.New("invalid endpoint config")
  17. }
  18. if domain[len(domain)-1:] == "/" {
  19. domain = domain[:len(domain)-1]
  20. }
  21. if !strings.HasPrefix("http://", domain) && !strings.HasPrefix("https://", domain) {
  22. //TLS is not hardcoded in proxy target domain
  23. if u.RequireTLS {
  24. domain = "https://" + domain
  25. } else {
  26. domain = "http://" + domain
  27. }
  28. }
  29. //Create a new proxy agent for this upstream
  30. path, err := url.Parse(domain)
  31. if err != nil {
  32. return err
  33. }
  34. proxy := dpcore.NewDynamicProxyCore(path, "", &dpcore.DpcoreOptions{
  35. IgnoreTLSVerification: u.SkipCertValidations,
  36. })
  37. u.proxy = proxy
  38. return nil
  39. }
  40. // IsReady return the proxy ready state of the upstream server
  41. // Return false if StartProxy() is not called on this upstream before
  42. func (u *Upstream) IsReady() bool {
  43. return u.proxy != nil
  44. }
  45. // Clone return a new deep copy object of the identical upstream
  46. func (u *Upstream) Clone() *Upstream {
  47. newUpstream := Upstream{}
  48. js, _ := json.Marshal(u)
  49. json.Unmarshal(js, &newUpstream)
  50. return &newUpstream
  51. }
  52. // ServeHTTP uses this upstream proxy router to route the current request
  53. func (u *Upstream) ServeHTTP(w http.ResponseWriter, r *http.Request, rrr *dpcore.ResponseRewriteRuleSet) error {
  54. //Auto rewrite to upstream origin if not set
  55. if rrr.ProxyDomain == "" {
  56. rrr.ProxyDomain = u.OriginIpOrDomain
  57. }
  58. return u.proxy.ServeHTTP(w, r, rrr)
  59. }
  60. // String return the string representations of endpoints in this upstream
  61. func (u *Upstream) String() string {
  62. return u.OriginIpOrDomain
  63. }