0

trying to do API versioning with a HTTP header in Spring WebFlux using RouterFunction.

With Spring WebFlux RouterFunction it can't be done using @GetMapping(headers = "API-VERSION=1.0.0") annotation.

my current attempt which isn't in my opinion a good one.

public Mono<ServerResponse> heartBeat(ServerRequest request) {
    final String apiVersion = request.headers().header("API-Version").get(0);

    switch (apiVersion) {
        case "1.0.0":
            return heartBeatV1_0_0(request);
        case "1.0.1":
            return heartBeatV1_0_1(request);
        default:
            return heartBeatV1_0_0(request);
    }
}

Is there a better way ?

Wesam
  • 932
  • 3
  • 15
  • 27
Marco
  • 3
  • 1

1 Answers1

0

I think your way is ok, but if you are looking for another approaches you could route your versions with RouterFunction. Something like this:

@Bean
RouterFunction<ServerResponse> routerFunction() {
    return RouterFunctions
            .route(
                    GET("/your/path").and(headers(headers -> testVersion(headers, "1.0.0"))),
                    /* handler function 1.0.0 */)
            .andRoute(
                    GET("/your/path").and(headers(headers -> testVersion(headers, "1.0.1"))),
                    /* handler function 1.0.1 */);
}

private boolean testVersion(ServerRequest.Headers headers, String version) {
    return headers.header("API-Version")
            .stream()
            .anyMatch(headerValue -> Objects.equals(headerValue, version));
}
Alexander Pankin
  • 3,787
  • 1
  • 13
  • 23