Server response with output from Future Object

我是研究僧i 提交于 2019-12-11 16:28:11

问题


i created a async/await function in another file thus its handler is returning a Future Object. Now i can't understand how to give response to client with content of that Future Object in Dart. I am using basic dart server with shelf package.Below is code where ht.handler('list') returns a Future Object and i want to send that string to client as response. But i am getting internal server error.

import 'dart:io';

import 'package:args/args.dart';
import 'package:shelf/shelf.dart' as shelf;
import 'package:shelf/shelf_io.dart' as io;
import 'HallTicket.dart' as ht;

// For Google Cloud Run, set _hostname to '0.0.0.0'.
const _hostname = 'localhost';

main(List<String> args) async {
  var parser = ArgParser()..addOption('port', abbr: 'p');
  var result = parser.parse(args);

  // For Google Cloud Run, we respect the PORT environment variable
  var portStr = result['port'] ?? Platform.environment['PORT'] ?? '8080';
  var port = int.tryParse(portStr);

  if (port == null) {
    stdout.writeln('Could not parse port value "$portStr" into a number.');
    // 64: command line usage error
    exitCode = 64;
    return;
  }

  var handler = const shelf.Pipeline()
      .addMiddleware(shelf.logRequests())
      .addHandler(_echoRequest);

  var server = await io.serve(handler, _hostname, port);
  print('Serving at http://${server.address.host}:${server.port}');
}

Future<shelf.Response> _echoRequest(shelf.Request request)async{
    shelf.Response.ok('Request for "${request.url}"\n'+await ht.handler('list'));
}

回答1:


The analyzer gives your the following warning for your _echoRequest method:

info: This function has a return type of 'Future', but doesn't end with a return statement.

And if you check the requirement for addHandler you will see it expects a handler to be returned.

So you need to add the return which makes it work on my machine:

Future<shelf.Response> _echoRequest(shelf.Request request) async {
  return shelf.Response.ok(
      'Request for "${request.url}"\n' + await ht.handler('list2'),
      headers: {'Content-Type': 'text/html'});
}


来源:https://stackoverflow.com/questions/59090393/server-response-with-output-from-future-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!