client.hpp 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #pragma once
  2. #include <nall/http/role.hpp>
  3. namespace nall::HTTP {
  4. struct Client : Role {
  5. inline auto open(const string& hostname, uint port = 80) -> bool;
  6. inline auto upload(const Request& request) -> bool;
  7. inline auto download(const Request& request) -> Response;
  8. inline auto close() -> void;
  9. ~Client() { close(); }
  10. private:
  11. int fd = -1;
  12. addrinfo* info = nullptr;
  13. };
  14. auto Client::open(const string& hostname, uint port) -> bool {
  15. addrinfo hint = {0};
  16. hint.ai_family = AF_UNSPEC;
  17. hint.ai_socktype = SOCK_STREAM;
  18. hint.ai_flags = AI_ADDRCONFIG;
  19. if(getaddrinfo(hostname, string{port}, &hint, &info) != 0) return close(), false;
  20. fd = socket(info->ai_family, info->ai_socktype, info->ai_protocol);
  21. if(fd < 0) return close(), false;
  22. if(connect(fd, info->ai_addr, info->ai_addrlen) < 0) return close(), false;
  23. return true;
  24. }
  25. auto Client::upload(const Request& request) -> bool {
  26. return Role::upload(fd, request);
  27. }
  28. auto Client::download(const Request& request) -> Response {
  29. Response response(request);
  30. Role::download(fd, response);
  31. return response;
  32. }
  33. auto Client::close() -> void {
  34. if(fd) {
  35. ::close(fd);
  36. fd = -1;
  37. }
  38. if(info) {
  39. freeaddrinfo(info);
  40. info = nullptr;
  41. }
  42. }
  43. }