DEV Community

loading...

Dart HttpServer With SSL

kyorohiro profile image kyorohiro (kiyohiro kawamura) ・2 min read

Last Time I got ssl from let's encrypt.

This time, execute a dart's https server at use ssl cert gotted last time.

import 'dart:io' as io;

const String cerbotWebRootPath = "/var/www/html";
const String privkeyPath = "/etc/letsencrypt/live/tetorica.net/privkey.pem";
const String fullchainPath = "/etc/letsencrypt/live/tetorica.net/fullchain.pem";
void main(List<String> arguments) async {
  try {
    print("start bind");
    onRequest(io.HttpRequest request) async {
      try {
        print("receive requested ${request.uri}");
        if (request.uri.path.startsWith("/.well-known/")) {
          var acmeChallengeFilePath = "" +
              cerbotWebRootPath +
              request.uri.path.replaceAll(RegExp("\\?.*"), "");
          acmeChallengeFilePath = acmeChallengeFilePath.replaceAll("/..", "/");
          var acmeChallengeFile = io.File(acmeChallengeFilePath);
          var acmeChallengeData = await acmeChallengeFile.readAsString();
          request.response.write(acmeChallengeData);
          request.response.close();
        }
        request.response.write("Hello");
        request.response.close();
      } catch (e, s) {
        print("${e}");
        print("${s}");
      }
    }

    var httpServer = await io.HttpServer.bind("0.0.0.0", 80);
    print("binded 80");
    httpServer.listen((request) {
      onRequest(request);
    });

    String key = io.Platform.script.resolve(privkeyPath).toFilePath();
    String crt = io.Platform.script.resolve(fullchainPath).toFilePath();
    io.SecurityContext context = new io.SecurityContext();
    context.useCertificateChain(crt);
    context.usePrivateKey(key, password: "");
    var httpsServer = await io.HttpServer.bindSecure("0.0.0.0", 443, context);
    print("binded 443");
    httpsServer.listen((request) {
      onRequest(request);
    });
  } catch (e, s) {
    print("${e}");
    print("${s}");
  }
}
Enter fullscreen mode Exit fullscreen mode

build and restart.

$ dart2native ./bin/main.dart
$ mv bin/main.exe /opt/main.exe
$ systemctl restart darthelloserver 
Enter fullscreen mode Exit fullscreen mode

and check from browser

https://tetorica.net/

Update ssl

check cron deamond

$ systemctl list-unit-files | grep cron
cron.service                           enabled         enabled  
Enter fullscreen mode Exit fullscreen mode

setup cron

$ crontab -u root -e
Enter fullscreen mode Exit fullscreen mode
00 04 03 * * certbot renew && systemctl restart darthelloserver 
Enter fullscreen mode Exit fullscreen mode

all code

https://github.com/kyorohiro/hao_dart_server_and_systemd/tree/dev03

Next

Dart's Http Server and Isolate

Discussion (0)

pic
Editor guide