service.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // This file is a part of the IncludeOS unikernel - www.includeos.org
  2. //
  3. // Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
  4. // and Alfred Bratterud
  5. //
  6. // Licensed under the Apache License, Version 2.0 (the "License");
  7. // you may not use this file except in compliance with the License.
  8. // You may obtain a copy of the License at
  9. //
  10. // http://www.apache.org/licenses/LICENSE-2.0
  11. //
  12. // Unless required by applicable law or agreed to in writing, software
  13. // distributed under the License is distributed on an "AS IS" BASIS,
  14. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. // See the License for the specific language governing permissions and
  16. // limitations under the License.
  17. #include <service>
  18. #include <os>
  19. #include <net/inet4>
  20. #include <mana/server.hpp>
  21. using namespace mana;
  22. using namespace std::string_literals;
  23. std::unique_ptr<mana::Server> server_;
  24. void Service::start(const std::string&)
  25. {
  26. /** IP STACK SETUP **/
  27. // Bring up IPv4 stack on network interface 0
  28. auto& stack = net::Inet4::ifconfig(5.0,
  29. [] (bool timeout) {
  30. printf("DHCP resolution %s\n", timeout ? "failed" : "succeeded");
  31. if (timeout)
  32. {
  33. /**
  34. * Default Manual config. Can only be done after timeout to work
  35. * with DHCP offers going to unicast IP (e.g. in GCE)
  36. **/
  37. net::Inet4::stack().network_config({ 10,0,0,42 }, // IP
  38. { 255,255,255,0 }, // Netmask
  39. { 10,0,0,1 }, // Gateway
  40. { 8,8,8,8 }); // DNS
  41. }
  42. });
  43. // Create a router
  44. Router router;
  45. // Setup a route on GET /
  46. router.on_get("/plaintext", [](auto, auto res) {
  47. res->source().set_status_code(http::OK);
  48. res->header().add_field(http::header::Server, "IncludeOS/" + OS::version());
  49. res->header().add_field(http::header::Content_Type, "text/plain");
  50. res->header().add_field(http::header::Date, "Mon, 01 Jan 1970 00:00:01 GMT");
  51. res->source().add_body("Hello, world!"s);
  52. res->send();
  53. });
  54. INFO("Router", "Registered routes:\n%s", router.to_string().c_str());
  55. // Create and setup the server
  56. server_ = std::make_unique<Server>(stack.tcp());
  57. server_->set_routes(router).listen(80);
  58. }