1
0

HttpService.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #include "HttpService.h"
  2. void HttpService::AddApi(const char* path, http_method method, http_api_handler handler) {
  3. std::shared_ptr<http_method_handlers> method_handlers = NULL;
  4. auto iter = api_handlers.find(path);
  5. if (iter == api_handlers.end()) {
  6. // add path
  7. method_handlers = std::shared_ptr<http_method_handlers>(new http_method_handlers);
  8. api_handlers[path] = method_handlers;
  9. }
  10. else {
  11. method_handlers = iter->second;
  12. }
  13. for (auto iter = method_handlers->begin(); iter != method_handlers->end(); ++iter) {
  14. if (iter->method == method) {
  15. // update
  16. iter->handler = handler;
  17. return;
  18. }
  19. }
  20. // add
  21. method_handlers->push_back(http_method_handler(method, handler));
  22. }
  23. int HttpService::GetApi(const char* url, http_method method, http_api_handler* handler) {
  24. // {base_url}/path?query
  25. const char* s = url;
  26. const char* c = base_url.c_str();
  27. while (*s != '\0' && *c != '\0' && *s == *c) {++s;++c;}
  28. if (*c != '\0') {
  29. return HTTP_STATUS_NOT_FOUND;
  30. }
  31. const char* e = s;
  32. while (*e != '\0' && *e != '?') ++e;
  33. std::string path = std::string(s, e);
  34. auto iter = api_handlers.find(path);
  35. if (iter == api_handlers.end()) {
  36. *handler = NULL;
  37. return HTTP_STATUS_NOT_FOUND;
  38. }
  39. auto method_handlers = iter->second;
  40. for (auto iter = method_handlers->begin(); iter != method_handlers->end(); ++iter) {
  41. if (iter->method == method) {
  42. *handler = iter->handler;
  43. return 0;
  44. }
  45. }
  46. *handler = NULL;
  47. return HTTP_STATUS_METHOD_NOT_ALLOWED;
  48. }