[Websersver]miniWebserver-(6)

👉🏻 주요변경 사항 / Major changes

✔️ 코드양이 많아져서 바뀐 부분만 설명합니다.
Since the amount of code has increased, I will only explain the parts that have changed.

✔️ 컴파일을 cmake로 변경
Change compilation to cmake

— g++ 로 컴파일 하는 방식에서 cmake를 통해서 컴파일 하도록 변경했습니다.
I changed the compilation method from using g++ to using cmake.

— 컴파일 해야하는 파일의 양이 많고 외부라이브러리를 사용해야한다면 cmake가 더 효율적입니다.
If you have a large amount of files to compile and need to use external libraries, CMake is more efficient.

— cmake를 먼저 설치합니다.(MacOS)

brew install cmake

— CMakeLists.txt 파일을 만들고 아래의 내용을 작성합니다.
Create a CMakeLists.txt file and write the following content.

# cmake최소버전지정 / Specify minimum CMake version
cmake_minimum_required(VERSION 3.10)

# 프로젝트 이름과 버전 설정 / Set project name and version
project(mini_webserver_6 VERSION 1.0)

# C++ 표준 버전 지정(c++20) / C++ Standard Version Specification (C++20)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED True)

# 실행 파일 이름, 소스 파일 / Executable file name, source file
add_executable(main
    Main.cpp
    Router.cpp
    Server.cpp
)

✔️ 헤더와 바디 리턴 기능 추가
Added header and body return functionality

— server.cpp에서 처리하던 헤더를 main.cpp에서 body와 header를 같이 넘겨 줍니다.
The header that was handled in server.cpp is passed to main.cpp along with the body.

— main.cpp

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

        // 라우터로부터 마임 타입과 본문을 받음
        // Receive MIME type and body from router
        auto [mime, body] = my_router.router(req);

        // HTTP 응답 헤더 생성
        // Generate HTTP response headers
        std::string response = "HTTP/1.1 200 OK\r\n";
        response += "Content-Type: " + mime + "\r\n";
        response += "Content-Length: " + std::to_string(body.size()) + "\r\n";
        response += "Connection: close\r\n";
        response += "\r\n"; // 헤더와 본문 구분자 / Header and body separator

        // 본문 추가 / Add body
        response += body;

        // 최종 응답 반환 / Return final response
        return response;
    });

— server.cpp


void Server::handle_client(int client_socket) {

 // ... 중략 / Omitted ...

        // HTTP 포맷 응답
        // std::string response = "HTTP/1.1 200 OK\r\n"
        //                        "Content-Type: text/html; charset=utf-8\r\n"
        //                        "Content-Length: " + std::to_string(html_content.size()) + "\r\n"
        //                        "\r\n" + html_content;
        //
        // main.cpp에서 넘어온 헤더 적용❗️
        // Apply header passed from main.cpp
        std::string response = html_content;

// ... 중략 / Omitted ...

}

✔️ 정적파일 서빙 기능 추가
Added static file serving feature

— public디렉토리 안에 html 파일을 사용 할 수 있습니다.
You can use HTML files inside the public directory.

— Router.cpp

std::pair<std::string, std::string> Router::router(const std::string& request) {

// ... 중략 / omitted ...

    std::string doc_root = "../public";
    std::string full_path = doc_root + path;

    // 경로가 / 이면 index.html로 매핑
    // If the path is /, map to index.html

    if (path == "/") {
        full_path = doc_root + "/index.html";
    }else if(path == "/test1"){
        full_path = doc_root + "/test1.html";
    }else if(path == "/test2"){
        full_path = doc_root + "/test2.html";
    }else{
        full_path = doc_root + "/index.html";
    }
    if (!std::filesystem::exists(full_path)) {
        return {"text/html", "<h1 style='color:red;'>404 Not Found</h1>"};
    }
// ... 중략 / omitted ...

    // 파일 확장자에 따른 마임타입 지정
    // Specify MIME type based on file extension
    std::string mime_type = "text/html; charset=UTF-8";
    if (full_path.ends_with(".css")) mime_type = "text/css";
    else if (full_path.ends_with(".js")) mime_type = "application/javascript";
    else if (full_path.ends_with(".json")) mime_type = "application/json";
    else if (full_path.ends_with(".png")) mime_type = "image/png";
    else if (full_path.ends_with(".jpg")) mime_type = "image/jpg";

}

✔️ 빌드 / build

MacBookAir build % cd ..  
MacBookAir mini_webserver_6 % cd build
MacBookAir build % cmake ..
-- Configuring done (0.1s)
-- Generating done (0.0s)
-- Build files have been written to: /Users/.../mini_webserver_6/build
MacBookAir build % make
[ 25%] Building CXX object CMakeFiles/main.dir/Main.cpp.o
[ 50%] Building CXX object CMakeFiles/main.dir/Router.cpp.o
[ 75%] Building CXX object CMakeFiles/main.dir/Server.cpp.o
[100%] Linking CXX executable main
[100%] Built target main
MacBookAir build % 

✔️ 실행 / Run

MacBookAir build % ./maiin

✔️ 브라우저 접속 / Access Browser

http://localhost:5080

Leave a Reply