dpcore_test.go 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package dpcore_test
  2. import (
  3. "net/url"
  4. "testing"
  5. "imuslab.com/zoraxy/mod/dynamicproxy/dpcore"
  6. )
  7. func TestReplaceLocationHost(t *testing.T) {
  8. tests := []struct {
  9. name string
  10. urlString string
  11. rrr *dpcore.ResponseRewriteRuleSet
  12. useTLS bool
  13. expectedResult string
  14. expectError bool
  15. }{
  16. {
  17. name: "Basic HTTP to HTTPS redirection",
  18. urlString: "http://example.com/resource",
  19. rrr: &dpcore.ResponseRewriteRuleSet{ProxyDomain: "example.com", OriginalHost: "proxy.example.com", UseTLS: true},
  20. useTLS: true,
  21. expectedResult: "https://proxy.example.com/resource",
  22. expectError: false,
  23. },
  24. {
  25. name: "Basic HTTPS to HTTP redirection",
  26. urlString: "https://proxy.example.com/resource",
  27. rrr: &dpcore.ResponseRewriteRuleSet{ProxyDomain: "proxy.example.com", OriginalHost: "proxy.example.com", UseTLS: false},
  28. useTLS: false,
  29. expectedResult: "http://proxy.example.com/resource",
  30. expectError: false,
  31. },
  32. {
  33. name: "No rewrite on mismatched domain",
  34. urlString: "http://anotherdomain.com/resource",
  35. rrr: &dpcore.ResponseRewriteRuleSet{ProxyDomain: "proxy.example.com", OriginalHost: "proxy.example.com", UseTLS: true},
  36. useTLS: true,
  37. expectedResult: "http://anotherdomain.com/resource",
  38. expectError: false,
  39. },
  40. {
  41. name: "Subpath trimming with HTTPS",
  42. urlString: "https://blog.example.com/post?id=1",
  43. rrr: &dpcore.ResponseRewriteRuleSet{ProxyDomain: "blog.example.com", OriginalHost: "proxy.example.com/blog", UseTLS: true},
  44. useTLS: true,
  45. expectedResult: "https://proxy.example.com/blog/post?id=1",
  46. expectError: false,
  47. },
  48. }
  49. for _, tt := range tests {
  50. t.Run(tt.name, func(t *testing.T) {
  51. result, err := dpcore.ReplaceLocationHost(tt.urlString, tt.rrr, tt.useTLS)
  52. if (err != nil) != tt.expectError {
  53. t.Errorf("Expected error: %v, got: %v", tt.expectError, err)
  54. }
  55. if result != tt.expectedResult {
  56. result, _ = url.QueryUnescape(result)
  57. t.Errorf("Expected result: %s, got: %s", tt.expectedResult, result)
  58. }
  59. })
  60. }
  61. }
  62. func TestReplaceLocationHostRelative(t *testing.T) {
  63. urlString := "api/"
  64. rrr := &dpcore.ResponseRewriteRuleSet{
  65. OriginalHost: "test.example.com",
  66. ProxyDomain: "private.com/test",
  67. UseTLS: true,
  68. }
  69. useTLS := true
  70. expectedResult := "api/"
  71. result, err := dpcore.ReplaceLocationHost(urlString, rrr, useTLS)
  72. if err != nil {
  73. t.Errorf("Error occurred: %v", err)
  74. }
  75. if result != expectedResult {
  76. t.Errorf("Expected: %s, but got: %s", expectedResult, result)
  77. }
  78. }