Singleton.h

ServerConfig.h

#ifndef AURORA_SERVERCONFIG_H
#define AURORA_SERVERCONFIG_H

#include "Singleton.h"

#include <string>
#include <map>

namespace aurora
{
    class ServerConfig
    {
    public:
        ServerConfig() = default;

        ~ServerConfig() = default;

        void init(const std::string &file);

        int getIntFieldValue(const std::string &fieldName);

        std::string getStringFiledValue(const std::string &fieldName);

    private:
        std::map<std::string, std::string> configMap;
    };
}

#define SERVER_CONFIG Singleton<ServerConfig>::instance()
#endif //AURORA_SERVERCONFIG_H

ServerConfig.cpp

#include "ServerConfig.h"

#include <fstream>
#include <cassert>
#include <cstring>

using namespace aurora;

void static removeSymbol(std::string &str)
{
    assert(!str.empty());
    str.erase(0, str.find_first_not_of(" \t"));
    str.erase(str.find_last_not_of(" \t") + 1);
}

void ServerConfig::init(const std::string &file)
{
    std::ifstream fileHandle(file);
    assert(fileHandle.is_open());

    std::string data;
    while (getline(fileHandle, data))
    {
        std::string::size_type pos = data.find('=');
        if (pos == std::string::npos)
            continue;

        std::string key = data.substr(0, pos);
        std::string value = data.substr(pos + strlen("="));
        removeSymbol(key);
        removeSymbol(value);
        configMap[key] = value;
    }
    fileHandle.close();
}

int ServerConfig::getIntFieldValue(const std::string &fieldName)
{
    auto value = configMap.find(fieldName);
    assert(value != configMap.end());
    return atoi(value->second.c_str());
}

std::string ServerConfig::getStringFiledValue(const std::string &fieldName)
{
    auto value = configMap.find(fieldName);
    assert(value != configMap.end());
    return value->second;
}

config

# logger
log_level = 0
log_thread_num = 1

# gs
gs_port = 18888

# ls
ls_port = 18889

# ws 
ws_port = 18890

# rs
rs_port = 18891

# open server time
open_server_time = 2020-04-21 00:50:00

main.cpp

#include "ServerConfig.h"

#include <iostream>

using namespace aurora;

int main(int argc, char *argv[])
{
    SERVER_CONFIG.init("./config");
    unsigned int logThreadNum = SERVER_CONFIG.getIntFieldValue("log_thread_num");
    unsigned int logLevel = SERVER_CONFIG.getIntFieldValue("log_level");
    int port = SERVER_CONFIG.getIntFieldValue("ls_port");
    std::cout << logThreadNum << " : " << logLevel << " : " << port << std::endl;
    return 0;
}