DEV Community

kyorohiro (kiyohiro kawamura)
kyorohiro (kiyohiro kawamura)

Posted on

Dart HttpServer With SSL

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

Top comments (0)