Skip to content

Commit b9838e4

Browse files
committed
Add cors middleware
1 parent a6bbff5 commit b9838e4

File tree

7 files changed

+158
-6
lines changed

7 files changed

+158
-6
lines changed

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,4 +27,5 @@ hs_err_pid*
2727
*.iml
2828
/_psd
2929
/.gradle
30-
/target
30+
/target
31+
_tmp

README.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -473,6 +473,22 @@ app.get("/port-test", (req, res) -> {
473473
## Existing Middlewares
474474
There are already some basic middlewares included, you can access these via static methods provided from `Middleware`.
475475

476+
#### CORS
477+
To realize a cors api yu can use the cors middleware.
478+
```java
479+
app.use(Middleware.cors());
480+
```
481+
You can use CorsOptions to specify origin, methods and more:
482+
```java
483+
CorsOptions corsOptions = new CorsOptions();
484+
corsOptions.setOrigin("https://mypage.com");
485+
corsOptions.setAllowCredentials(true);
486+
corsOptions.setHeaders(new String[]{"GET", "POST"});
487+
corsOptions.setFilter(req -> // Custom validation if cors should be applied);
488+
489+
app.use(Middleware.cors());
490+
```
491+
476492
#### Provide static Files
477493
If you want to allocate some files, like librarys, css, images etc. you can use the [static](https://github.com/Simonwep/java-express/blob/master/src/express/middleware/Middleware.java) middleware. But you can also provide other files like mp4 etc.
478494
Example:
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package express.middleware;
2+
3+
import express.http.HttpRequestHandler;
4+
import express.http.RequestMethod;
5+
import express.http.request.Request;
6+
import express.http.response.Response;
7+
8+
public class Cors implements HttpRequestHandler {
9+
10+
private final CorsOptions options;
11+
12+
public Cors(CorsOptions options) {
13+
this.options = options;
14+
}
15+
16+
@Override
17+
public void handle(Request req, Response res) {
18+
CorsOptions.Filter filter = this.options.getFilter();
19+
20+
// Check if filter is present
21+
if (filter != null && !filter.shouldBypass(req)) {
22+
return;
23+
}
24+
25+
// Acquire options
26+
boolean ac = this.options.isAllowCredentials();
27+
String origins = this.options.getOrigin();
28+
String[] headers = this.options.getHeaders();
29+
RequestMethod[] methods = this.options.getMethods();
30+
31+
// Apply headers
32+
res.setHeader("Access-Control-Allow-Credentials", Boolean.toString(ac));
33+
res.setHeader("Access-Control-Allow-Origin", origins != null ? origins : "*");
34+
res.setHeader("Access-Control-Allow-Methods", methods != null ? join(methods) : "*");
35+
res.setHeader("Access-Control-Request-Headers", headers != null ? join(headers) : "*");
36+
}
37+
38+
private String join(Object[] objects) {
39+
StringBuilder sb = new StringBuilder();
40+
41+
for (Object o : objects) {
42+
sb.append(o.toString()).append(", ");
43+
}
44+
45+
String string = sb.toString();
46+
return string.substring(0, string.length() - 2);
47+
}
48+
}
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
package express.middleware;
2+
3+
import express.http.RequestMethod;
4+
import express.http.request.Request;
5+
6+
public class CorsOptions {
7+
8+
private boolean allowCredentials;
9+
private RequestMethod[] methods;
10+
private String[] headers;
11+
private String origin;
12+
private Filter filter;
13+
14+
public CorsOptions(boolean allowCredentials, String origin, String[] headers, RequestMethod[] methods, Filter filter) {
15+
this.allowCredentials = allowCredentials;
16+
this.origin = origin;
17+
this.filter = filter;
18+
this.methods = methods;
19+
this.headers = headers;
20+
}
21+
22+
public CorsOptions() {
23+
this(false, null, null, null, null);
24+
}
25+
26+
public String[] getHeaders() {
27+
return headers;
28+
}
29+
30+
public void setHeaders(String[] headers) {
31+
this.headers = headers;
32+
}
33+
34+
public String getOrigin() {
35+
return origin;
36+
}
37+
38+
public boolean isAllowCredentials() {
39+
return allowCredentials;
40+
}
41+
42+
public void setAllowCredentials(boolean allowCredentials) {
43+
this.allowCredentials = allowCredentials;
44+
}
45+
46+
public void setOrigin(String origin) {
47+
this.origin = origin;
48+
}
49+
50+
public RequestMethod[] getMethods() {
51+
return methods;
52+
}
53+
54+
public void setMethods(RequestMethod[] methods) {
55+
this.methods = methods;
56+
}
57+
58+
public Filter getFilter() {
59+
return filter;
60+
}
61+
62+
public void setFilter(Filter filter) {
63+
this.filter = filter;
64+
}
65+
66+
interface Filter {
67+
boolean shouldBypass(Request req);
68+
}
69+
}

src/main/java/express/middleware/FileProvider.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ public final class FileProvider implements HttpRequestHandler {
3434
Path rootDir = Paths.get(root);
3535

3636
if (!Files.exists(rootDir) || !Files.isDirectory(rootDir)) {
37-
throw new IOException(rootDir + " does not exists or isn't an directory.");
37+
throw new IOException(rootDir + " does not exists or isn't a directory.");
3838
}
3939

4040
this.root = rootDir.toAbsolutePath().toString();
@@ -118,8 +118,9 @@ public void handle(Request req, Response res) {
118118
}
119119

120120
private void finish(Path file, Request req, Response res) {
121-
if (options.getHandler() != null)
121+
if (options.getHandler() != null) {
122122
options.getHandler().handle(req, res);
123+
}
123124

124125
try {
125126

src/main/java/express/middleware/Middleware.java

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
package express.middleware;
22

3-
43
import java.io.IOException;
54

65
/**
@@ -49,4 +48,22 @@ public static FileProvider statics(String directoryPath, FileProviderOptions sta
4948
return new FileProvider(directoryPath, staticOptions);
5049
}
5150

51+
/**
52+
* CORS Middleware
53+
*
54+
* @param options Cors options
55+
* @return
56+
*/
57+
public static Cors cors(CorsOptions options) {
58+
return new Cors(options);
59+
}
60+
61+
/**
62+
* CORS Middleware with default settings
63+
*
64+
* @return
65+
*/
66+
public static Cors cors() {
67+
return new Cors(new CorsOptions());
68+
}
5269
}

src/main/java/express/utils/Utils.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,8 @@ public static String streamToString(InputStream is) {
3434
}
3535

3636
return sb.toString();
37-
} catch (IOException ignored) {
38-
}
37+
} catch (IOException ignored) { }
38+
3939
return null;
4040
}
4141

0 commit comments

Comments
 (0)