Created
March 18, 2024 15:34
-
-
Save Dev-Owl/243294a84650d35acc53d419442d247d to your computer and use it in GitHub Desktop.
Simple HTTP logger written in dart using shelf
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:io'; | |
import 'package:intl/intl.dart'; | |
import 'package:shelf/shelf.dart'; | |
import 'package:shelf/shelf_io.dart' as shelf_io; | |
void main(List<String> arguments) async { | |
var port = 8088; | |
var ip = "172.16.200.22"; | |
if (arguments.any((e) => e.startsWith('port='))) { | |
final rawArgument = | |
arguments.where((element) => element.startsWith('port=')).first; | |
port = int.parse(rawArgument.replaceAll('port=', '')); | |
} | |
if (arguments.any((e) => e.startsWith('ip='))) { | |
final rawArgument = | |
arguments.where((element) => element.startsWith('ip=')).first; | |
ip = rawArgument.replaceAll('ip=', ''); | |
} | |
var handler = | |
const Pipeline().addMiddleware(logRequests()).addHandler(_echoRequest); | |
var server = await shelf_io.serve(handler, ip, port); | |
// Enable content compression | |
server.autoCompress = true; | |
print('Serving at http://${server.address.host}:${server.port}'); | |
} | |
Future<Response> _echoRequest(Request request) async { | |
final content = await request.readAsString(); | |
final now = DateTime.now(); | |
final DateFormat formatter = DateFormat('yyyy-MM-dd-HH-mm-ss'); | |
final String formatted = formatter.format(now); | |
await File('$formatted.txt').writeAsString(content); | |
return Response.ok(null); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment