RemoteAddress.vala 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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_request(HttpContext context) throws Error {
  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 HttpStringResult(json)
  28. .set_header("Content-Type", "application/json")
  29. .set_header("Access-Control-Allow-Origin", "*");
  30. // Log the request to console
  31. print(@"[$(get_current_time())] $(request.method) $(request.raw_path) from $(remote_address ?? "unknown")\n");
  32. return response;
  33. }
  34. private static string get_current_time() {
  35. var now = new DateTime.now_local();
  36. return now.format("%Y-%m-%d %H:%M:%S");
  37. }
  38. }