aboutsummaryrefslogtreecommitdiffhomepage
path: root/server.dart
blob: eb5307d5594ba8e04343e926a94a229374531e54 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import 'dart:convert';
import 'dart:io';

void main() async {
  const int port = 6969;
  final requests = await HttpServer.bind('localhost', port);
  print('Started server bind to localhost:$port');
  await for (final request in requests) {
    print('uri: ${request.uri}');
    if (request.method == 'GET') {
      print('Processing GET method');
      processGet(request);
    } else if (request.method == 'POST') {
      print('Processing POST method');
      processPost(request);
    }
  }
}

void processGet(HttpRequest request) async {
  var filename = request.uri.toString().substring(1);
  bool exist = await File(filename).exists();
  String data = '';
  if (exist) {
    var data = await File(filename).readAsString();
    print('Sent data:');
    print(data);
  } else {
    File(filename).writeAsString('');
    print('Created file $filename');
  }
  request.response
    ..statusCode = HttpStatus.ok
    ..write(data)
    ..close();
}

void processPost(HttpRequest request) async {
  var filename = request.uri.path.substring(1);
  String data = await utf8.decoder.bind(request).join();
  File(filename).writeAsString(data);
  print('Received data:');
  print(data);
}