[Webserver]miniWebserver-(11)

👉🏻 주요 변경사항은 아래와 같습니다.
The major changes are as follows.

✔️ ❗️ 표시된 부분이 변경사항입니다.
The parts marked with ❗️ are the changes.

✔️ 가상호스트 기능을 추가했습니다.
Added virtual host functionality.

✔️ HttpsServer.cpp에 스레드 정리시간을 좀 더 추가했습니다.
I added some more thread cleanup time to HttpsServer.cpp.

✔️ 서버종료 부분에 try-catch 부분이 추가되었습니다.
A try-catch block has been added to the server termination section.

👉🏻코드 / Code

✔️가상호스트 / Virtual Host

— main.cpp

    // virtusl host 라우터 / virtual host router❗️
    Router virtual_router("../public_virtual");
    virtual_router.add_route("GET","/test1", "test1.html");
    virtual_router.add_route("POST","/test2", "test2.html");

    // virtual host http(5080) server host map❗️
    static std::map<std::string, Router*> vhost_routers = {
        {"yourmainhost.domain.org", &server1_router},
        {"yourvirtualhost.domain.org", &virtual_router},
        {"localhost", &server1_router},
        {"127.0.0.1", &server1_router},
        {"192.168.0.100", &server1_router}
    };

    // virtual host https(6443) server host map❗️
    static std::map<std::string, Router*> vhost_https_routers = {
        {"yourmainhost.domain.org", &server2_router},
        {"yourvirtualhost.domain.org"", &virtual_router},
        {"localhost", &server2_router},
        {"127.0.0.1", &server2_router},
        {"192.168.0.100", &server2_router}
    };

        std::pair<std::string, std::string> result;


        // 요청 헤더 전체 읽기 및 Host 헤더 파싱❗️
        // Read all request headers and parse Host headers
        std::string line;
        std::string host;

        // 헤더에서 개행문자 제거용 ❗️
        // For removing newline characters from headers
        std::string dummy;
        std::getline(req_stream, dummy);

        // 요청 헤더 파싱(req stream의 값을 읽어서 line 변수에 한 줄씩 복사)❗️
        // Parse request headers (read values ​​from the req stream and copy them line by line to the line variable)
        while (std::getline(req_stream, line) && line != "\r" && !line.empty()) {
            // "Host:" 찾기 (대소문자 무관하게 검사하는 것이 안전함)
            if (line.compare(0, 5, "Host:") == 0 || line.compare(0, 5, "host:") == 0) {
                host = line.substr(5);
                // 공백 및 \r 제거
                host.erase(0, host.find_first_not_of(" \t"));
                size_t last = host.find_last_not_of(" \t\r\n");
                if (last != std::string::npos) host.erase(last + 1);

                // std::cout << "[DEBUG] https Host Found: " << host << std::endl << std::flush;
            }
        }

server2.set_handler([&](const std::string& req) {

... 중략 / Skipping the middle ...

        // 포트 번호 제거하여 도메인명만 추출❗️
        // Remove port number to extract only the domain name
        std::string host_normalized = host;
        size_t pos = host.find(':');
        if (pos != std::string::npos) {
            host_normalized = host.substr(0, pos);
        }

        // 라우터 선택: 해당 호스트의 라우터 찾기, 없으면 기본 라우터❗️
        // Select Router: Find the router for the host, if none exists, use the default router
        Router* router_ptr = &server2_router; // 기본값 / default value
        auto it = vhost_https_routers.find(host_normalized);
        if (it != vhost_https_routers.end()) {
            router_ptr = it->second;
        }


        if (method == "GET" || method == "POST" || method == "PUT" || method == "DELETE" || method == "FETCH") {

            // 이전코드 / previous code
            //result = server2_router.router(method, path);
            //
            // virtual host 적용 / apply virtual host❗️
            result = router_ptr->router(method, path);
        }

... 중략 / Skipping the middle ...

}

✔️ 스레드 정리시간 추가 / Add thread cleanup time

  // 스레드 정리시간 추가❗️
  // Add thread cleanup time
  std::this_thread::sleep_for(std::chrono::milliseconds(300));

👉🏻 빌드 / Build

cd build
cmake ..
make

👉🏻 실행 / Run

./main

👉🏻 브라우저 접속 / Access Browser

http://yourmainhost.domain.org:5080
http://yourvirtualhost.domain.org:5080

https://yourmainhost.domain.org:6444
https://yourvirtualhost.domain.org:6444

Leave a Reply