LoginSignup
3
0

More than 1 year has passed since last update.

DartでHTTPサーバを立てる

Last updated at Posted at 2021-11-30

FlutterでOAuthを実装しようとしたときに、OAuthを使おうとしたサービスがredirect_urlにCustom URL Schemeが使えなかった(http://~, https://以外許可されていなかった)ので、
リダイレクト先のHTTPサーバを立ててあげようとしたときのメモ。

import 'dart:io';

Future<void> main() async {
  final server =
      await HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, 8080, shared: true);
  listenForServerResponse(server);
}

listenForServerResponse(HttpServer server) {
  server.listen((HttpRequest request) async {
    final uri = request.uri;
    request.response
      ..statusCode = 200
      ..headers.set("Content-Type", ContentType.HTML.mimeType);

    final code = uri.queryParameters["code"];
    final error = uri.queryParameters["error"];
    await request.response.close();
    if (code != null) {
      print(code);
    } else if (error != null) {
      print(error);
    }
  });
}

エミュレータとかで試してないけど、こんなコードでRedirectされてきたURLのQueryParameterからCodeが取れるはず。

  • InternetAddress.LOOPBACK_IP_V4127.0.0.1になっているはず
  • HttpServer.bindの2つ目の引数でポートを指定する。この場合8080
  • shared: trueは他のHttpServerが同じアドレスにBindできるかどうかのフラグ(?)っぽい。別インスタンスのHttpServerを同じポートで複数建てられるってコト?!

実行サンプル

> curl 'http://localhost:8080/?code=12345'


StatusCode        : 200
StatusDescription : OK
Content           :
RawContent        : HTTP/1.1 200 OK
                    x-frame-options: SAMEORIGIN
                    x-xss-protection: 1; mode=block
                    x-content-type-options: nosniff
                    Content-Length: 0
                    Content-Type: text/html


Forms             : {}
Headers           : {[x-frame-options, SAMEORIGIN], [x-xss-protection, 1; mode=block], [x-content-type-options, nosniff], [Content-Length, 0]...}
Images            : {}
InputFields       : {}
Links             : {}
ParsedHtml        : mshtml.HTMLDocumentClass
RawContentLength  : 0
> dart .\main.dart
12345
3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0