0
Fork 0
mirror of https://github.com/caddyserver/caddy.git synced 2024-12-23 22:27:38 -05:00

httpserver: Implement {sever_port} placeholder (#2424)

This commit is contained in:
Max Heyer 2019-01-25 21:54:33 +01:00 committed by Toby Allen
parent a7aeb979be
commit 7f546e529e
2 changed files with 39 additions and 0 deletions

View file

@ -506,6 +506,16 @@ func (r *replacer) getSubstitution(key string) string {
return cert.NotBefore.Format("Jan 02 15:04:05 2006 MST") return cert.NotBefore.Format("Jan 02 15:04:05 2006 MST")
} }
return r.emptyValue return r.emptyValue
case "{server_port}":
_, port, err := net.SplitHostPort(r.request.Host)
if err != nil {
if r.request.TLS != nil {
return "443"
} else {
return "80"
}
}
return port
default: default:
// {labelN} // {labelN}
if strings.HasPrefix(key, "{label") { if strings.HasPrefix(key, "{label") {

View file

@ -127,6 +127,7 @@ func TestReplace(t *testing.T) {
{"{label1} {label2} {label3} {label4}", "localhost local - -"}, {"{label1} {label2} {label3} {label4}", "localhost local - -"},
{"Label with missing number is {label} or {labelQQ}", "Label with missing number is - or -"}, {"Label with missing number is {label} or {labelQQ}", "Label with missing number is - or -"},
{"\\{ 'hostname': '{hostname}' \\}", "{ 'hostname': '" + hostname + "' }"}, {"\\{ 'hostname': '{hostname}' \\}", "{ 'hostname': '" + hostname + "' }"},
{"{server_port}", "80"},
} }
for _, c := range testCases { for _, c := range testCases {
@ -159,6 +160,33 @@ func TestReplace(t *testing.T) {
} }
} }
func TestCustomServerPort(t *testing.T) {
w := httptest.NewRecorder()
recordRequest := NewResponseRecorder(w)
reader := strings.NewReader(`{"username": "dennis"}`)
request, err := http.NewRequest("POST", "http://localhost.local:8000/?foo=bar", reader)
if err != nil {
t.Fatalf("Failed to make request: %v", err)
}
ctx := context.WithValue(request.Context(), OriginalURLCtxKey, *request.URL)
request = request.WithContext(ctx)
repl := NewReplacer(request, recordRequest, "-")
testCase := struct {
template string
expect string
}{
template: "{server_port}",
expect: "8000",
}
if expected, actual := testCase.expect, repl.Replace(testCase.template); expected != actual {
t.Errorf("for template '%s', expected '%s', got '%s'", testCase.template, expected, actual)
}
}
func TestTlsReplace(t *testing.T) { func TestTlsReplace(t *testing.T) {
w := httptest.NewRecorder() w := httptest.NewRecorder()
recordRequest := NewResponseRecorder(w) recordRequest := NewResponseRecorder(w)
@ -246,6 +274,7 @@ eqp31wM9il1n+guTNyxJd+FzVAH+hCZE5K+tCgVDdVFUlDEHHbS/wqb2PSIoouLV
{"{tls_client_v_end}", cVEnd}, {"{tls_client_v_end}", cVEnd},
{"{tls_client_v_remain}", cVRemain}, {"{tls_client_v_remain}", cVRemain},
{"{tls_client_v_start}", cVStart}, {"{tls_client_v_start}", cVStart},
{"{server_port}", "443"},
} }
for _, c := range testCases { for _, c := range testCases {