UriAdapter.java 3.19 KB
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;
    }

}