Skip to content

Commit

Permalink
refractor: simplify http_server
Browse files Browse the repository at this point in the history
  • Loading branch information
MiaoHN committed Jan 10, 2025
1 parent 5d6f895 commit 7cf1e49
Show file tree
Hide file tree
Showing 22 changed files with 109 additions and 105 deletions.
90 changes: 38 additions & 52 deletions example/http_server/http_server.cpp
Original file line number Diff line number Diff line change
@@ -1,72 +1,58 @@
#include "gudov/http/http_server.h"

#include <yaml-cpp/yaml.h>

#include <fstream>
#include <string>

#include "gudov/config.h"
#include "gudov/log.h"

gudov::Logger::ptr g_logger = LOG_ROOT();

bool exist_file(const std::string& filename) {
std::ifstream f(filename);
return !f.bad();
}

std::string read_file(const std::string& filename) {
std::ifstream f(filename);
return std::string((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
}
#include "gudov/gudov.h"
#include "gudov/http/http.h"

using gudov::Address;
using gudov::Config;
using gudov::EnvMgr;
using gudov::FSUtil;
using gudov::IOManager;
using gudov::Logger;
using gudov::LogLevel;
using gudov::http::HttpRequest;
using gudov::http::HttpResponse;
using gudov::http::HttpServer;
using gudov::http::HttpSession;

Logger::ptr g_logger = LOG_ROOT();

void run() {
if (exist_file("conf/http_server.yml")) {
YAML::Node root = YAML::LoadFile("conf/http_server.yml");
gudov::Config::LoadFromYaml(root);
LOG_INFO(g_logger) << "Successfully load config file 'conf/http_server.yml'";
} else {
LOG_INFO(g_logger) << "config file 'conf/http_server.yml' doesn't exists, "
"use default configurations";
}
gudov::Address::ptr addr = gudov::Address::LookupAnyIPAddress("0.0.0.0:8020");
if (!addr) {
LOG_ERROR(g_logger) << "get address error";
return;
}
g_logger->SetLevel(LogLevel::INFO);

gudov::http::HttpServer::ptr http_server(new gudov::http::HttpServer(true));
while (!http_server->Bind(addr)) {
HttpServer::ptr server(new HttpServer(true));
Address::ptr addr = Address::LookupAnyIPAddress("0.0.0.0:8020");

while (!server->Bind(addr)) {
LOG_ERROR(g_logger) << "Bind " << *addr << " fail";
sleep(1);
sleep(2);
}

auto servlet_dispatcher = http_server->GetServletDispatch();
auto sd = server->GetServletDispatch();

servlet_dispatcher->addServlet("/", [](gudov::http::HttpRequest::ptr req, gudov::http::HttpResponse::ptr rsp,
gudov::http::HttpSession::ptr session) {
rsp->SetBody(read_file("html/index.html"));
sd->AddServlet("/", [](HttpRequest::ptr req, HttpResponse::ptr rsp, HttpSession::ptr session) {
rsp->SetBody(FSUtil::ReadFile("html/index.html"));
return 0;
});

servlet_dispatcher->addServlet(
"/index.html",
[](gudov::http::HttpRequest::ptr req, gudov::http::HttpResponse::ptr rsp, gudov::http::HttpSession::ptr session) {
rsp->SetBody(read_file("html/index.html"));
return 0;
});
sd->AddServlet("/index.html", [](HttpRequest::ptr req, HttpResponse::ptr rsp, HttpSession::ptr session) {
rsp->SetBody(FSUtil::ReadFile("html/index.html"));
return 0;
});

servlet_dispatcher->addGlobServlet("/*", [](gudov::http::HttpRequest::ptr req, gudov::http::HttpResponse::ptr rsp,
gudov::http::HttpSession::ptr session) {
rsp->SetBody(read_file("html/404.html"));
sd->AddGlobServlet("/*", [](HttpRequest::ptr req, HttpResponse::ptr rsp, HttpSession::ptr session) {
rsp->SetBody(FSUtil::ReadFile("html/404.html"));
return 0;
});

http_server->Start();
server->Start();
}

int main(int argc, char** argv) {
gudov::IOManager iom(5);
EnvMgr::GetInstance()->Init(argc, argv);
Config::LoadFromConfDir(EnvMgr::GetInstance()->GetConfigPath());

IOManager iom(1, true, "http_server");

iom.Schedule(run);

return 0;
}
2 changes: 1 addition & 1 deletion gudov/bytearray.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -413,7 +413,7 @@ bool ByteArray::WriteToFile(const std::string& name) const {
std::ofstream ofs;
ofs.open(name, std::ios::trunc | std::ios::binary);
if (!ofs) {
LOG_ERROR(g_logger) << "writeToFile name=" << name << " error , errno=" << errno << " errstr=" << strerror(errno);
LOG_ERROR(g_logger) << "WriteToFile name=" << name << " error , errno=" << errno << " errstr=" << strerror(errno);
return false;
}

Expand Down
2 changes: 1 addition & 1 deletion gudov/config.h
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@ class ConfigVar : public ConfigVarBase {

std::string GetTypeName() const override { return typeid(T).name(); }

uint64_t addListener(onChangeCallback callback) {
uint64_t AddListener(onChangeCallback callback) {
static uint64_t s_fun_id = 0;
RWMutexType::WriteLock lock(mutex_);
++s_fun_id;
Expand Down
14 changes: 13 additions & 1 deletion gudov/gudov.h
Original file line number Diff line number Diff line change
@@ -1,11 +1,23 @@
#pragma once

#include "address.h"
#include "bytearray.h"
#include "config.h"
#include "env.h"
#include "fiber.h"
#include "http/http.h"
#include "http/http_connection.h"
#include "http/http_parser.h"
#include "http/http_server.h"
#include "http/http_session.h"
#include "http/servlet.h"
#include "iomanager.h"
#include "log.h"
#include "macro.h"
#include "scheduler.h"
#include "singleton.h"
#include "socket.h"
#include "socket_stream.h"
#include "tcp_server.h"
#include "thread.h"
#include "util.h"
#include "util.h"
6 changes: 3 additions & 3 deletions gudov/hook.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ struct _HookIniter {
hookInit();
s_connectTimeout = g_tcpConnectTimeout->GetValue();

g_tcpConnectTimeout->addListener([](const int& oldValue, const int& newValue) {
g_tcpConnectTimeout->AddListener([](const int& oldValue, const int& newValue) {
LOG_INFO(g_logger) << "tcp connect timeout changed from " << oldValue << " to " << newValue;
s_connectTimeout = newValue;
});
Expand Down Expand Up @@ -164,7 +164,7 @@ static ssize_t doIO(int fd, OriginFun fun, const std::string& hook_fun_name, uin
// 为 fd 添加一个协程并且 hold
int rt = iom->AddEvent(fd, (gudov::IOManager::Event)(event));
if (GUDOV_UNLICKLY(rt)) {
LOG_ERROR(g_logger) << hook_fun_name << " addEvent(" << fd << ", " << event << ")";
LOG_ERROR(g_logger) << hook_fun_name << " AddEvent(" << fd << ", " << event << ")";
if (timer) {
timer->Cancel();
}
Expand Down Expand Up @@ -313,7 +313,7 @@ int connectWithTimeout(int fd, const struct sockaddr* addr, socklen_t addrlen, u
if (timer) {
timer->Cancel();
}
LOG_ERROR(g_logger) << "connect addEvent(" << fd << ", WRITE) error";
LOG_ERROR(g_logger) << "connect AddEvent(" << fd << ", WRITE) error";
}

int error = 0;
Expand Down
14 changes: 7 additions & 7 deletions gudov/http/http_connection.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ HttpConnection::HttpConnection(Socket::ptr sock, bool owner) : SocketStream(sock

HttpConnection::~HttpConnection() { LOG_DEBUG(g_logger) << "HttpConnection::~HttpConnection"; }

HttpResponse::ptr HttpConnection::recvResponse() {
HttpResponse::ptr HttpConnection::RecvResponse() {
HttpResponseParser::ptr parser(new HttpResponseParser);
uint64_t buff_size = HttpRequestParser::GetHttpRequestBufferSize();
// uint64_t buff_size = 100;
Expand Down Expand Up @@ -123,11 +123,11 @@ HttpResponse::ptr HttpConnection::recvResponse() {
return parser->GetData();
}

int HttpConnection::sendRequest(HttpRequest::ptr rsp) {
int HttpConnection::SendRequest(HttpRequest::ptr rsp) {
std::stringstream ss;
ss << *rsp;
std::string data = ss.str();
return writeFixSize(data.c_str(), data.size());
return WriteFixSize(data.c_str(), data.size());
}

HttpResult::ptr HttpConnection::DoGet(const std::string& url, uint64_t timeout_ms,
Expand Down Expand Up @@ -214,7 +214,7 @@ HttpResult::ptr HttpConnection::DoRequest(HttpRequest::ptr req, Uri::ptr uri, ui
}
sock->SetRecvTimeout(timeout_ms);
HttpConnection::ptr conn = std::make_shared<HttpConnection>(sock);
int rt = conn->sendRequest(req);
int rt = conn->SendRequest(req);
if (rt == 0) {
return std::make_shared<HttpResult>((int)HttpResult::Error::SEND_CLOSE_BY_PEER, nullptr,
"send request closed by peer: " + addr->ToString());
Expand All @@ -224,7 +224,7 @@ HttpResult::ptr HttpConnection::DoRequest(HttpRequest::ptr req, Uri::ptr uri, ui
(int)HttpResult::Error::SEND_SOCKET_ERROR, nullptr,
"send request socket error errno=" + std::to_string(errno) + " errstr=" + std::string(strerror(errno)));
}
auto rsp = conn->recvResponse();
auto rsp = conn->RecvResponse();
if (!rsp) {
return std::make_shared<HttpResult>(
(int)HttpResult::Error::TIMEOUT, nullptr,
Expand Down Expand Up @@ -382,7 +382,7 @@ HttpResult::ptr HttpConnectionPool::doRequest(HttpRequest::ptr req, uint64_t tim
"pool host:" + host_ + " port:" + std::to_string(port_));
}
sock->SetRecvTimeout(timeout_ms);
int rt = conn->sendRequest(req);
int rt = conn->SendRequest(req);
if (rt == 0) {
return std::make_shared<HttpResult>((int)HttpResult::Error::SEND_CLOSE_BY_PEER, nullptr,
"send request closed by peer: " + sock->GetRemoteAddress()->ToString());
Expand All @@ -392,7 +392,7 @@ HttpResult::ptr HttpConnectionPool::doRequest(HttpRequest::ptr req, uint64_t tim
(int)HttpResult::Error::SEND_SOCKET_ERROR, nullptr,
"send request socket error errno=" + std::to_string(errno) + " errstr=" + std::string(strerror(errno)));
}
auto rsp = conn->recvResponse();
auto rsp = conn->RecvResponse();
if (!rsp) {
return std::make_shared<HttpResult>(
(int)HttpResult::Error::TIMEOUT, nullptr,
Expand Down
4 changes: 2 additions & 2 deletions gudov/http/http_connection.h
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,9 @@ class HttpConnection : public SocketStream {

static HttpResult::ptr DoRequest(HttpRequest::ptr req, Uri::ptr uri, uint64_t timeout_ms);

HttpResponse::ptr recvResponse();
HttpResponse::ptr RecvResponse();

int sendRequest(HttpRequest::ptr req);
int SendRequest(HttpRequest::ptr req);

private:
uint64_t create_time_ = 0;
Expand Down
8 changes: 4 additions & 4 deletions gudov/http/http_parser.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -45,16 +45,16 @@ struct _RequestSizeIniter {
s_http_response_buffer_size = g_http_response_buffer_size->GetValue();
s_http_response_max_body_size = g_http_response_max_body_size->GetValue();

g_http_request_buffer_size->addListener(
g_http_request_buffer_size->AddListener(
[](const uint64_t& ov, const uint64_t& nv) { s_http_request_buffer_size = nv; });

g_http_request_max_body_size->addListener(
g_http_request_max_body_size->AddListener(
[](const uint64_t& ov, const uint64_t& nv) { s_http_request_max_body_size = nv; });

g_http_response_buffer_size->addListener(
g_http_response_buffer_size->AddListener(
[](const uint64_t& ov, const uint64_t& nv) { s_http_response_buffer_size = nv; });

g_http_response_max_body_size->addListener(
g_http_response_max_body_size->AddListener(
[](const uint64_t& ov, const uint64_t& nv) { s_http_response_max_body_size = nv; });
}
};
Expand Down
4 changes: 2 additions & 2 deletions gudov/http/http_server.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ void HttpServer::HandleClient(Socket::ptr client) {
LOG_DEBUG(g_logger) << "HandleClient " << *client;
HttpSession::ptr session(new HttpSession(client));
do {
auto req = session->recvRequest();
auto req = session->RecvRequest();
if (!req) {
LOG_DEBUG(g_logger) << "recv http request fail, errno=" << errno << " errstr=" << strerror(errno)
<< " cliet:" << *client << " keep_alive=" << is_keep_alive_;
Expand All @@ -27,7 +27,7 @@ void HttpServer::HandleClient(Socket::ptr client) {
HttpResponse::ptr rsp(new HttpResponse(req->GetVersion(), req->IsClose() || !is_keep_alive_));
rsp->SetHeader("Server", GetName());
dispatch_->handle(req, rsp, session);
session->sendResponse(rsp);
session->SendResponse(rsp);

if (!is_keep_alive_ || req->IsClose()) {
break;
Expand Down
6 changes: 3 additions & 3 deletions gudov/http/http_session.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ namespace http {

HttpSession::HttpSession(Socket::ptr sock, bool owner) : SocketStream(sock, owner) {}

HttpRequest::ptr HttpSession::recvRequest() {
HttpRequest::ptr HttpSession::RecvRequest() {
HttpRequestParser::ptr parser(new HttpRequestParser);
uint64_t buff_size = HttpRequestParser::GetHttpRequestBufferSize();
std::shared_ptr<char> buffer(new char[buff_size], [](char* ptr) { delete[] ptr; });
Expand Down Expand Up @@ -62,11 +62,11 @@ HttpRequest::ptr HttpSession::recvRequest() {
return parser->GetData();
}

int HttpSession::sendResponse(HttpResponse::ptr rsp) {
int HttpSession::SendResponse(HttpResponse::ptr rsp) {
std::stringstream ss;
ss << *rsp;
std::string data = ss.str();
return writeFixSize(data.c_str(), data.size());
return WriteFixSize(data.c_str(), data.size());
}

} // namespace http
Expand Down
4 changes: 2 additions & 2 deletions gudov/http/http_session.h
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ class HttpSession : public SocketStream {

HttpSession(Socket::ptr sock, bool owner = true);

HttpRequest::ptr recvRequest();
HttpRequest::ptr RecvRequest();

int sendResponse(HttpResponse::ptr rsp);
int SendResponse(HttpResponse::ptr rsp);
};

} // namespace http
Expand Down
10 changes: 5 additions & 5 deletions gudov/http/servlet.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -22,17 +22,17 @@ int32_t ServletDispatch::handle(HttpRequest::ptr request, HttpResponse::ptr resp
return 0;
}

void ServletDispatch::addServlet(const std::string& uri, Servlet::ptr slt) {
void ServletDispatch::AddServlet(const std::string& uri, Servlet::ptr slt) {
RWMutexType::WriteLock lock(mutex_);
datas_[uri] = slt;
}

void ServletDispatch::addServlet(const std::string& uri, FunctionServlet::callback callback) {
void ServletDispatch::AddServlet(const std::string& uri, FunctionServlet::callback callback) {
RWMutexType::WriteLock lock(mutex_);
datas_[uri].reset(new FunctionServlet(callback));
}

void ServletDispatch::addGlobServlet(const std::string& uri, Servlet::ptr slt) {
void ServletDispatch::AddGlobServlet(const std::string& uri, Servlet::ptr slt) {
RWMutexType::WriteLock lock(mutex_);
for (auto it = globs_.begin(); it != globs_.end(); ++it) {
if (it->first == uri) {
Expand All @@ -43,8 +43,8 @@ void ServletDispatch::addGlobServlet(const std::string& uri, Servlet::ptr slt) {
globs_.push_back(std::make_pair(uri, slt));
}

void ServletDispatch::addGlobServlet(const std::string& uri, FunctionServlet::callback callback) {
return addGlobServlet(uri, FunctionServlet::ptr(new FunctionServlet(callback)));
void ServletDispatch::AddGlobServlet(const std::string& uri, FunctionServlet::callback callback) {
return AddGlobServlet(uri, FunctionServlet::ptr(new FunctionServlet(callback)));
}

void ServletDispatch::DelServlet(const std::string& uri) {
Expand Down
8 changes: 4 additions & 4 deletions gudov/http/servlet.h
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,10 @@ class ServletDispatch : public Servlet {
ServletDispatch();
virtual int32_t handle(HttpRequest::ptr request, HttpResponse::ptr response, HttpSession::ptr session) override;

void addServlet(const std::string& uri, Servlet::ptr slt);
void addServlet(const std::string& uri, FunctionServlet::callback callback);
void addGlobServlet(const std::string& uri, Servlet::ptr slt);
void addGlobServlet(const std::string& uri, FunctionServlet::callback callback);
void AddServlet(const std::string& uri, Servlet::ptr slt);
void AddServlet(const std::string& uri, FunctionServlet::callback callback);
void AddGlobServlet(const std::string& uri, Servlet::ptr slt);
void AddGlobServlet(const std::string& uri, FunctionServlet::callback callback);

void DelServlet(const std::string& uri);
void DelGlobServlet(const std::string& uri);
Expand Down
2 changes: 1 addition & 1 deletion gudov/iomanager.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ int IOManager::AddEvent(int fd, Event event, std::function<void()> callback) {
FdContext::MutexType::Locker lock2(fd_ctx->mutex);
if (fd_ctx->events & event) {
// 已经添加过该事件
LOG_ERROR(g_logger) << "addEvent assert fd=" << fd << " event=" << event << " fdCtx.event=" << fd_ctx->events;
LOG_ERROR(g_logger) << "AddEvent assert fd=" << fd << " event=" << event << " fdCtx.event=" << fd_ctx->events;
GUDOV_ASSERT(!(fd_ctx->events & event));
}

Expand Down
Loading

0 comments on commit 7cf1e49

Please sign in to comment.