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

Initial functionality for default function routing #3691

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/*
* Copyright 2013-2025 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.cloud.gateway.server.mvc.config;

import static org.springframework.cloud.gateway.server.mvc.handler.GatewayRouterFunctions.route;
import static org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions.fn;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.function.RouterFunction;
import org.springframework.web.servlet.function.ServerResponse;

@Configuration
@ConditionalOnClass(name = "org.springframework.cloud.function.context.FunctionCatalog")
@ConditionalOnProperty(name = "spring.cloud.gateway.function.enabled", havingValue = "true", matchIfMissing = true)
public class DefaultFunctionConfiguration {

@Bean
RouterFunction<ServerResponse> gatewayToFunctionRouter() {
// @formatter:off
return route("functionroute")
.POST("/{path}/{name}", fn("{path}/{name}"))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What are the two parts for?

.POST("/{path}", fn("{path}"))
.GET("/{path}/{name}", fn("{path}/{name}"))
.GET("/{path}", fn("{path}"))
.build();
// @formatter:on
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,11 @@

import jakarta.servlet.ServletException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.function.context.FunctionCatalog;
import org.springframework.cloud.function.context.catalog.SimpleFunctionRegistry.FunctionInvocationWrapper;
import org.springframework.cloud.gateway.server.mvc.GatewayMvcClassPathWarningAutoConfiguration;
import org.springframework.cloud.gateway.server.mvc.common.MvcUtils;
import org.springframework.cloud.gateway.server.mvc.config.RouteProperties;
import org.springframework.cloud.stream.function.StreamOperations;
Expand All @@ -43,6 +46,8 @@

public abstract class HandlerFunctions {

private static final Log log = LogFactory.getLog(GatewayMvcClassPathWarningAutoConfiguration.class);

private HandlerFunctions() {

}
Expand All @@ -56,12 +61,29 @@ public static HandlerFunction<ServerResponse> fn(RouteProperties routeProperties
public static HandlerFunction<ServerResponse> fn(String functionName) {
Assert.hasText(functionName, "'functionName' must not be empty");
return request -> {
String expandedFunctionName = MvcUtils.expand(request, functionName);
FunctionCatalog functionCatalog = MvcUtils.getApplicationContext(request).getBean(FunctionCatalog.class);
FunctionInvocationWrapper function = functionCatalog.lookup(expandedFunctionName,
request.headers().accept().stream().map(MimeType::toString).toArray(String[]::new));
String expandedFunctionName = MvcUtils.expand(request, functionName);
FunctionInvocationWrapper function;
Object body = null;
if (expandedFunctionName.contains("/")) {
String[] functionBodySplit = expandedFunctionName.split("/");
function = functionCatalog.lookup(functionBodySplit[0],
request.headers().accept().stream().map(MimeType::toString).toArray(String[]::new));
if (function != null && function.isSupplier()) {
log.warn("Supplier must not have any arguments. Supplier: '" + function.getFunctionDefinition()
+ "' has '" + functionBodySplit[1] + "' as an argument which is ignored.");
}
body = functionBodySplit[1];
}
else {
function = functionCatalog.lookup(expandedFunctionName,
request.headers().accept().stream().map(MimeType::toString).toArray(String[]::new));
}

if (function != null) {
Object body = function.isSupplier() ? null : request.body(function.getRawInputType());
if (body == null) {
body = function.isSupplier() ? null : request.body(function.getRawInputType());
}
return processRequest(request, function, body, false, Collections.emptyList(), Collections.emptyList());
}
return ServerResponse.notFound().build();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
org.springframework.cloud.gateway.server.mvc.GatewayServerMvcAutoConfiguration
org.springframework.cloud.gateway.server.mvc.GatewayMvcClassPathWarningAutoConfiguration
org.springframework.cloud.gateway.server.mvc.handler.GatewayMultipartAutoConfiguration
org.springframework.boot.autoconfigure.web.client.RestClientAutoConfiguration
org.springframework.boot.autoconfigure.web.client.RestClientAutoConfiguration
org.springframework.cloud.gateway.server.mvc.config.DefaultFunctionConfiguration
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
/*
* Copyright 2013-2025 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.cloud.gateway.server.mvc.handler;

import static org.assertj.core.api.Assertions.assertThat;

import java.util.Locale;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.gateway.server.mvc.test.client.TestRestClient;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;

@SpringBootTest(properties = {}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class DefaultRouteFunctionHandlerTests {

@Autowired
private TestRestClient restClient;

@Test
public void testSupplierWorks() {
restClient.get()
.uri("/hello")
.accept(MediaType.TEXT_PLAIN)
.exchange()
.expectStatus()
.isOk()
.expectBody(String.class)
.isEqualTo("hello");
}

@Test
public void testFunctionWorksGET() {
restClient.get()
.uri("/upper/bob")
.accept(MediaType.TEXT_PLAIN)
.exchange()
.expectStatus()
.isOk()
.expectBody(String.class)
.isEqualTo("BOB");
}

@Test
public void testFunctionWorksPOST() {
restClient.post()
.uri("/upper")
.accept(MediaType.APPLICATION_JSON)
.bodyValue("bob")
.exchange()
.expectStatus()
.isOk()
.expectBody(String.class)
.isEqualTo("BOB");
}

@Test
public void testConsumerWorksGET() {
restClient.get().uri("/consume/hello").accept(MediaType.TEXT_PLAIN).exchange().expectStatus().isAccepted();
assertThat(TestConfiguration.consumerInvoked).isTrue();
}

@Test
public void testConsumerWorksPOST() {
restClient.post()
.uri("/consume")
.accept(MediaType.APPLICATION_JSON)
.bodyValue("hello")
.exchange()
.expectStatus()
.isAccepted();
assertThat(TestConfiguration.consumerInvoked).isTrue();
}

@SpringBootConfiguration
@EnableAutoConfiguration
protected static class TestConfiguration {

static boolean consumerInvoked;

@Bean
Function<String, String> upper() {
return s -> s.toUpperCase(Locale.ROOT);
}

@Bean
Consumer<String> consume() {
return s -> {
consumerInvoked = false;
assertThat(s).isEqualTo("hello");
consumerInvoked = true;
};
}

@Bean
Supplier<String> hello() {
return () -> "hello";
}

}

}
Loading