Is there anyway to get current locale in Spring Cloud Gateway? I use LocaleContextHolder.getLocale()
to get user's locale but it's always return default locale en
.
Thank for your help!
@Component
public class ClientVersionGatewayFilterFactory extends AbstractGatewayFilterFactory<ClientVersionGatewayFilterFactory.Config> {
private final MessageSource messageSource;
public ClientVersionGatewayFilterFactory(MessageSource messageSource) {
super(Config.class);
this.messageSource = messageSource;
}
@Override
public GatewayFilter apply(Config config) {
return new GatewayFilter() {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
Locale locale = LocaleContextHolder.getLocale();
String message = messageSource.getMessage("test", null, locale);
exchange.getResponse().getHeaders().set("X-Custom-Locale", locale.getLanguage());
exchange.getResponse().getHeaders().set("X-Custom-Test", message);
return exchange.getResponse().setComplete();
}
};
}
public static class Config {
}
}
I found a way to workaround.
Locale locale = LocaleContextHolder.getLocale(exchange.getLocaleContext());
String message = messageSource.getMessage("test", null, locale);
Is there anyone have better solutions?