RemoteAddress.vala 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using Astralis;
  2. using Invercargill;
  3. using Invercargill.DataStructures;
  4. /**
  5. * RemoteAddress Example
  6. *
  7. * Demonstrates accessing client remote address information.
  8. */
  9. // Endpoint that responds with client information
  10. public class RemoteAddressEndpoint : Object, Endpoint {
  11. public async HttpResult handle_request(HttpContext context, RouteContext route) throws Error {
  12. var request = context.request;
  13. // Access the remote address
  14. var remote_address = request.remote_address;
  15. // Build JSON response with client info using string interpolation
  16. var json = @"{
  17. \"method\": \"$(request.method)\",
  18. \"path\": \"$(request.raw_path)\",
  19. \"remote_address\": \"$(remote_address ?? "unknown")\",
  20. \"user_agent\": \"$(request.user_agent ?? "unknown")\"
  21. }";
  22. var response = new HttpStringResult(json)
  23. .set_header("Content-Type", "application/json")
  24. .set_header("Access-Control-Allow-Origin", "*");
  25. // Log the request to console
  26. print(@"[$(get_current_time())] $(request.method) $(request.raw_path) from $(remote_address ?? "unknown")\n");
  27. return response;
  28. }
  29. private static string get_current_time() {
  30. var now = new DateTime.now_local();
  31. return now.format("%Y-%m-%d %H:%M:%S");
  32. }
  33. }
  34. void main() {
  35. var application = new WebApplication(8080);
  36. application.container.register_scoped<Endpoint>(() => new RemoteAddressEndpoint())
  37. .with_metadata<EndpointRoute>(new EndpointRoute("*"));
  38. print("Remote Address Example Server running on port 8080\n");
  39. print("Try: http://localhost:8080/\n");
  40. application.run();
  41. }