UriAdapter.java
3.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package com.peony.netty.web;
import com.peony.netty.http.Request;
import com.peony.netty.http.Response;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URI;
import java.util.*;
public class UriAdapter {
private static Logger logger = LoggerFactory.getLogger(UriAdapter.class);
private static Map<String[], Route> routeMap = new HashMap<>();
public static void get(final String path, final Route route) {
String[] paths = path.split("/");
routeMap.put(paths, route);
}
public static boolean adapter(String uri, HttpRequest request, FullHttpResponse response) {
URI u = URI.create(uri);
String path = u.getPath();
logger.info("path: " + u.getPath() + " query: " + u.getQuery());
for (Map.Entry<String[], Route> entry : routeMap.entrySet()) {
String[] key = entry.getKey();
Route route = entry.getValue();
PathMatchResult pathMatchResult = pathMatch(key, path);
if (pathMatchResult.success()) {
logger.info("匹配成功: " + Arrays.toString(pathMatchResult.getCustomPaths()) + " uri: " + path);
for (Map.Entry<String, String> param : pathMatchResult.getParams().entrySet()) {
logger.info("匹配参数: " + param.getKey() + " : " + param.getValue());
}
Request req = new Request(request);
Response resp = new Response(response);
req.setPathMatchResult(pathMatchResult);
Object handle = route.handle(req, resp);
if (handle instanceof String) {
String content = (String) handle;
response.content().writeBytes(Unpooled.wrappedBuffer(content.getBytes()));
}
return true;
}
}
logger.warn("匹配失败:" + path);
return false;
}
public static PathMatchResult pathMatch(String[] customPaths, String path) {
PathMatchResult pathMatchResult = new PathMatchResult();
String[] paths = path.substring(1).split("/");
List<String> pathList = new ArrayList<>();
for (String subPath: paths) {
pathList.add(subPath);
}
if (pathList.size() != customPaths.length) {
pathMatchResult.setSuccess(false);
return pathMatchResult;
}
Map<String, String> params = new HashMap<>();
for (int i = 0; i < customPaths.length; i++) {
String s = pathList.get(i);
String customPath = customPaths[i];
if (customPath.startsWith(":")) {
params.put(customPath.substring(1), s);
} else if (!customPath.equals(s)) {
pathMatchResult.setSuccess(false);
return pathMatchResult;
}
if (i == customPaths.length - 1) {
pathMatchResult.setCustomPaths(customPaths);
pathMatchResult.setParams(params);
}
}
pathMatchResult.setSuccess(true);
return pathMatchResult;
}
}