Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -208,23 +208,35 @@ func isValidProto(proto string) bool {
return false
}

// firstValidProto returns the left-most valid scheme token from a possibly
// comma-separated header value (e.g. "https, http" from multi-proxy hops).
func firstValidProto(header string) string {
for _, part := range strings.Split(header, ",") {
p := strings.TrimSpace(part)
if isValidProto(p) {
return p
}
}
return ""
}

// Scheme returns the HTTP protocol scheme, `http` or `https`.
func (c *Context) Scheme() string {
// Can't use `r.Request.URL.Scheme`
// See: https://groups.google.com/forum/#!topic/golang-nuts/pMUkBlQBDF0
if c.IsTLS() {
return "https"
}
if scheme := c.request.Header.Get(HeaderXForwardedProto); isValidProto(scheme) {
if scheme := firstValidProto(c.request.Header.Get(HeaderXForwardedProto)); scheme != "" {
return scheme
}
if scheme := c.request.Header.Get(HeaderXForwardedProtocol); isValidProto(scheme) {
if scheme := firstValidProto(c.request.Header.Get(HeaderXForwardedProtocol)); scheme != "" {
return scheme
}
if ssl := c.request.Header.Get(HeaderXForwardedSsl); ssl == "on" {
return "https"
}
if scheme := c.request.Header.Get(HeaderXUrlScheme); isValidProto(scheme) {
if scheme := firstValidProto(c.request.Header.Get(HeaderXUrlScheme)); scheme != "" {
return scheme
}
return "http"
Expand Down
16 changes: 16 additions & 0 deletions context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1140,6 +1140,22 @@ func TestContext_Scheme(t *testing.T) {
},
expect: "HTTPS",
},
{
name: "uses left-most token from comma-separated X-Forwarded-Proto",
givenIsTLS: false,
givenHeaders: http.Header{
HeaderXForwardedProto: []string{"https, http"},
},
expect: "https",
},
{
name: "skips invalid tokens in comma-separated X-Forwarded-Proto",
givenIsTLS: false,
givenHeaders: http.Header{
HeaderXForwardedProto: []string{"ftp, https"},
},
expect: "https",
},
{
name: "uses X-Forwarded-Proto ws",
givenIsTLS: false,
Expand Down
Loading