Skip to content

Commit

Permalink
fix redirectHTTP middleware, add bypass.user_agents option
Browse files Browse the repository at this point in the history
  • Loading branch information
yusing committed Feb 28, 2025
1 parent 9c04065 commit 6892963
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 10 deletions.
40 changes: 31 additions & 9 deletions internal/net/gphttp/middleware/redirect_http.go
Original file line number Diff line number Diff line change
@@ -1,29 +1,51 @@
package middleware

import (
"net"
"net/http"
"strings"

"github.com/yusing/go-proxy/internal/common"
"github.com/yusing/go-proxy/internal/logging"
)

type redirectHTTP struct{}
type redirectHTTP struct {
Bypass struct {
UserAgents []string
}
}

var RedirectHTTP = NewMiddleware[redirectHTTP]()

// before implements RequestModifier.
func (redirectHTTP) before(w http.ResponseWriter, r *http.Request) (proceed bool) {
func (m *redirectHTTP) before(w http.ResponseWriter, r *http.Request) (proceed bool) {
if r.TLS != nil {
return true
}

if len(m.Bypass.UserAgents) > 0 {
ua := r.UserAgent()
for _, uaBypass := range m.Bypass.UserAgents {
if strings.Contains(ua, uaBypass) {
return true
}
}
}

r.URL.Scheme = "https"
host := r.Host
if i := strings.Index(host, ":"); i != -1 {
host = host[:i] // strip port number if present
host, _, err := net.SplitHostPort(r.Host)
if err != nil {
host = r.Host
}
r.URL.Host = host + ":" + common.ProxyHTTPSPort
logging.Debug().Str("url", r.URL.String()).Msg("redirect to https")
http.Redirect(w, r, r.URL.String(), http.StatusTemporaryRedirect)
return true

if common.ProxyHTTPSPort != "443" {
r.URL.Host = host + ":" + common.ProxyHTTPSPort
} else {
r.URL.Host = host
}

http.Redirect(w, r, r.URL.String(), http.StatusMovedPermanently)

logging.Debug().Str("url", r.URL.String()).Str("user_agent", r.UserAgent()).Msg("redirect to https")
return false
}
2 changes: 1 addition & 1 deletion internal/net/gphttp/middleware/redirect_http_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ func TestRedirectToHTTPs(t *testing.T) {
reqURL: types.MustParseURL("http://example.com"),
})
ExpectNoError(t, err)
ExpectEqual(t, result.ResponseStatus, http.StatusTemporaryRedirect)
ExpectEqual(t, result.ResponseStatus, http.StatusPermanentRedirect)
ExpectEqual(t, result.ResponseHeaders.Get("Location"), "https://example.com:"+common.ProxyHTTPSPort)
}

Expand Down

0 comments on commit 6892963

Please sign in to comment.