RemoteAddress.vala 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 string route { get { return "*"; } }
  12. public Method[] methods { owned get { return { Method.GET }; } }
  13. public async HttpResult handle_request(HttpContext context, RouteInformation route) throws Error {
  14. var request = context.request;
  15. // Access the remote address
  16. var remote_address = request.remote_address;
  17. // Build JSON response with client info using string interpolation
  18. var json = @"{
  19. \"method\": \"$(request.method)\",
  20. \"path\": \"$(request.raw_path)\",
  21. \"remote_address\": \"$(remote_address ?? "unknown")\",
  22. \"user_agent\": \"$(request.user_agent ?? "unknown")\"
  23. }";
  24. var response = new HttpStringResult(json)
  25. .set_header("Content-Type", "application/json")
  26. .set_header("Access-Control-Allow-Origin", "*");
  27. // Log the request to console
  28. print(@"[$(get_current_time())] $(request.method) $(request.raw_path) from $(remote_address ?? "unknown")\n");
  29. return response;
  30. }
  31. private static string get_current_time() {
  32. var now = new DateTime.now_local();
  33. return now.format("%Y-%m-%d %H:%M:%S");
  34. }
  35. }
  36. void main() {
  37. var router = new EndpointRouter()
  38. .add_endpoint(new RemoteAddressEndpoint());
  39. var pipeline = new Pipeline()
  40. .add_component(router);
  41. var server = new Server(8080, pipeline);
  42. print("Remote Address Example Server running on port 8080\n");
  43. print("Try: http://localhost:8080/\n");
  44. server.run();
  45. }