1
0
mirror of https://github.com/flutter/samples.git synced 2025-11-08 22:09:06 +00:00
Files
samples/code_sharing/server/bin/server.dart
Craig Labenz fc6222ebc8 Add code sharing sample (#1444)
* code-sharing boilerplate

* initial commit of code-sharing logic

* documentation improvements

* added code-sharing to samples.yaml

* Updated counter UI to visually indicate communication with the server

* added code_sharing to CI

* CI changes to code_sharing

* fixed test with DI

* formatting

* added shared module to CI

* adds forgotten CI change
2022-10-05 08:47:30 -07:00

37 lines
1.1 KiB
Dart

import 'dart:convert';
import 'dart:io';
import 'package:shared/shared.dart';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart';
import 'package:shelf_router/shelf_router.dart';
int count = 0;
// Configure routes.
final _router = Router()
..post('/', _incrementHandler)
..get('/', _getValueHandler);
Future<Response> _incrementHandler(Request request) async {
final incr = Increment.fromJson(json.decode(await request.readAsString()));
count += incr.by;
return Response.ok(json.encode(Count(count).toJson()));
}
Response _getValueHandler(Request request) =>
Response.ok(json.encode(Count(count).toJson()));
void main(List<String> args) async {
// Use any available host or container IP (usually `0.0.0.0`).
final ip = InternetAddress.anyIPv4;
// Configure a pipeline that logs requests.
final handler = Pipeline().addMiddleware(logRequests()).addHandler(_router);
// For running in containers, we respect the PORT environment variable.
final port = int.parse(Platform.environment['PORT'] ?? '8080');
final server = await serve(handler, ip, port);
print('Server listening on port ${server.port}');
}