Allow sending SSE events without data

Prior to this commit, the SseBuilder API in WebMvc.fn would only allow
to send Server-Sent Events with `data:` items in them. The spec doesnn't
disallow this and other specifications rely on such patterns to signal
the completion of a stream, like:

```
event:next
data:some data

event:complete

```

This commit adds a new `send()` method without any argument that sends
the buffered content (id, event comment and retry) without data.

Fixes: gh-32270
This commit is contained in:
Brian Clozel
2024-02-14 16:56:52 +01:00
parent 2284254d39
commit f9ae54d91e
3 changed files with 51 additions and 16 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-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.
@@ -32,8 +32,10 @@ import org.springframework.web.testfixture.servlet.MockHttpServletResponse;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link ServerResponse.SseBuilder}.
* @author Arjen Poutsma
* @author Sebastien Deleuze
* @author Brian Clozel
*/
class SseServerResponseTests {
@@ -151,6 +153,26 @@ class SseServerResponseTests {
assertThat(this.mockResponse.getContentAsString()).isEqualTo(expected);
}
@Test
void sendWithoutData() throws Exception {
ServerResponse response = ServerResponse.sse(sse -> {
try {
sse.event("custom").send();
}
catch (IOException ex) {
throw new UncheckedIOException(ex);
}
});
ServerResponse.Context context = Collections::emptyList;
ModelAndView mav = response.writeTo(this.mockRequest, this.mockResponse, context);
assertThat(mav).isNull();
String expected = "event:custom\n\n";
assertThat(this.mockResponse.getContentAsString()).isEqualTo(expected);
}
private static final class Person {