Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor header appending logic for better readability #3676

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2016-2019 the original author or authors.
* Copyright 2016-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -35,6 +35,7 @@
import java.util.Set;
import java.util.Vector;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;

import jakarta.servlet.ReadListener;
Expand Down Expand Up @@ -403,30 +404,27 @@ private void proxy() {

private void appendXForwarded(URI uri) {
// Append the legacy headers if they were already added upstream
String host = headers.getFirst("x-forwarded-host");
if (host == null) {
return;
appendXForwardedHeader("x-forwarded-host", () -> uri.getHost());
appendXForwardedHeader("x-forwarded-proto", () -> uri.getScheme());
}

private void appendXForwardedHeader(String headerName, Supplier<String> uriValue) {
String existingValue = headers.getFirst(headerName);
if (existingValue != null) {
StringBuilder builder = new StringBuilder(existingValue);
builder.append(",").append(uriValue.get());
headers.set(headerName, builder.toString());
}
host = host + "," + uri.getHost();
headers.set("x-forwarded-host", host);
String proto = headers.getFirst("x-forwarded-proto");
if (proto == null) {
return;
}
proto = proto + "," + uri.getScheme();
headers.set("x-forwarded-proto", proto);
}

private void appendForwarded(URI uri) {
String forwarded = headers.getFirst("forwarded");
if (forwarded != null) {
forwarded = forwarded + ",";
}
else {
forwarded = "";
String forwarded = headers.getFirst("forwarded");
StringBuilder builder = new StringBuilder();
if (StringUtils.hasText(forwarded)) {
builder.append(forwarded).append(",");
}
forwarded = forwarded + forwarded(uri, webRequest.getHeader("host"));
headers.set("forwarded", forwarded);
builder.append(forwarded(uri, webRequest.getHeader("host")));
headers.set("forwarded", builder.toString());
}

private String forwarded(URI uri, String hostHeader) {
Expand Down
Loading