模块划分
合理编写模块的 demo.h、demo.cc
下例为C++为后端服务编写的探活检测服务
health_server.h
#ifndef HEALTH_SERVER_H
#define HEALTH_SERVER_H
#include <iostream>
//#include "utils/flags.h"
void health_server( const std::string &health_host , const std::string &health_port );
#endif
- 必加
#ifndef
: 预处理功能(宏定义,文件包含和条件编译)中的条件编译,主要用来防止重复编译,“multiple define”错误
- .h中的其它预处理功能
include***
,遵循最小使用原则
,如上例 仅使用std::string
,则对应 仅加入#include<iostream>
.cc
文件也需要添加 对应#include "health_server.h"
文件
health_server.cc
#include <dirent.h>
#include <fstream>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <atomic>
#include <memory>
#include <thread>
#include <iostream>
#include "health_server.h"
#include "./http_server.h"
mg_serve_http_opts oppo::HttpServer::s_server_option;
std::atomic<bool> server_stop(true);
std::unordered_map<std::string, oppo::ReqHandler> oppo::HttpServer::s_handler_map;
std::unordered_set<mg_connection *> oppo::HttpServer::s_websocket_session_set;
static bool HandleHealth(std::string url, std::string body,
mg_connection *c, oppo::OnRspCallback rsp_callback)
{
if (!server_stop)
rsp_callback(c, "OK");
else
rsp_callback(c, "STOP");
return true;
}
static bool HandleStop(std::string url, std::string body,
mg_connection *c, oppo::OnRspCallback rsp_callback)
{
if (!server_stop) {
server_stop = true;
rsp_callback(c, "STOP OK");
}
else {
rsp_callback(c, "IS STOP");
}
return true;
}
static bool HandleStart(std::string url, std::string body,
mg_connection *c, oppo::OnRspCallback rsp_callback)
{
if (server_stop) {
server_stop = false;
rsp_callback(c, "START OK");
}
else {
rsp_callback(c, "IS START");
}
return true;
}
void health_server( const std::string &health_host , const std::string &health_port ){
std::string health_address(health_host + ":" + health_port);
auto health_server = std::unique_ptr<oppo::HttpServer>(new oppo::HttpServer);
std::thread http_thread([&health_server, health_address]() {
health_server->Init(health_address);
health_server->AddHandler("/asr/health", HandleHealth);
health_server->AddHandler("/asr/stop", HandleStop);
health_server->AddHandler("/asr/start", HandleStart);
health_server->Start();
});
http_thread.join();
}
标签:std,string,cc,C++,server,health,模块,include,rsp
From: https://www.cnblogs.com/lhx9527/p/16717059.html