RemoteAddress.vala 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using Astralis;
  2. using Invercargill;
  3. using Invercargill.DataStructures;
  4. public class RemoteAddressExample : Object {
  5. public static int main(string[] args) {
  6. // Create a simple handler that logs the client's remote address
  7. var handler = new SimpleHttpHandler();
  8. // Start the server on port 8080
  9. var server = new Server(8080, handler);
  10. server.run();
  11. return 0;
  12. }
  13. }
  14. // Simple handler that responds with client information
  15. public class SimpleHttpHandler : Object, RequestHandler {
  16. public async HttpResult handle(HttpContext context) {
  17. var request = context.request;
  18. // Access the remote address
  19. var remote_address = request.remote_address;
  20. // Build JSON response with client info using string interpolation
  21. var json = @"{
  22. \"method\": \"$(request.method)\",
  23. \"path\": \"$(request.raw_path)\",
  24. \"remote_address\": \"$(remote_address ?? "unknown")\",
  25. \"user_agent\": \"$(request.user_agent ?? "unknown")\"
  26. }";
  27. var response = new BufferedHttpResult.from_string(
  28. json,
  29. StatusCode.OK,
  30. get_json_headers()
  31. );
  32. // Log the request to console
  33. print(@"[$(get_current_time())] $(request.method) $(request.raw_path) from $(remote_address ?? "unknown")");
  34. return response;
  35. }
  36. private static string get_current_time() {
  37. var now = new DateTime.now_local();
  38. return now.format("%Y-%m-%d %H:%M:%S");
  39. }
  40. private static Catalogue<string, string> get_json_headers() {
  41. var headers = new Catalogue<string, string>();
  42. headers.add("Content-Type", "application/json");
  43. headers.add("Access-Control-Allow-Origin", "*");
  44. return headers;
  45. }
  46. }