I am just trying to improve my coding and designing skills in C++ and for that I am trying to solve same age old problem of mapping a http request to method.
Could you guys please look at my program and point me to mistakes I am doing with design and coding style?
resource.hpp
#include <functional>
#include <string>
typedef std::function<void(void)> Handler;
enum class RequestMethod {
GET,
PUT,
POST,
DELETE
};
class Resource {
public:
Resource() {}
void SetMethodHandler(const RequestMethod method, const Handler& callback);
Handler GetMethodHandler();
void SetPath(const std::string& path);
std::string& GetPath();
private:
Resource(const Resource& other) = delete;
Resource& operator=(Resource& rhs) = delete;
std::string m_path;
RequestMethod m_method;
Handler m_callback;
};
resource.cpp
#include "resource.hpp"
void Resource::SetPath(const std::string& path) {
m_path = path;
}
std::string& Resource :: GetPath() {
return m_path;
}
void Resource :: SetMethodHandler(RequestMethod method, const Handler& callback) {
m_method = method;
m_callback = callback;
}
Handler Resource :: GetMethodHandler() {
return m_callback;
}
main.cpp
#include "resource.hpp"
#include <memory>
#include <iostream>
#include <map>
void LoginMethodHandler() {
std::cout << "Code here to handle a login request." << std::endl;
}
int main() {
using ResourceSharedPtr = std::shared_ptr<Resource>;
ResourceSharedPtr resource_ptr = std::make_shared<Resource>();
resource_ptr->SetPath("/login");
resource_ptr->SetMethodHandler(RequestMethod::GET, LoginMethodHandler);
/* call to method handler */
/* ideally in full blown application, logic will be search for path and
method and call approriate handler */
resource_ptr->GetMethodHandler()();
auto path_map = std::make_pair(resource_ptr->GetPath(),resource_ptr);
return 0;
}