DEV Community

loading...

Dart HttpServer & Systemd

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

How to setup dart's http server.
Dartlang support httpserver's function at dart:io.

like this.

  • ./bin/main.dart
import 'dart:io' as io;

void main(List<String> arguments) async {
  try {
    print("start bind");
    var httpServer = await io.HttpServer.bind("0.0.0.0", 80);
    print("binded");
    await for (var request in httpServer) {
      print("receive requested ${request.uri}");
      request.response.write("Hello");
      request.response.close();
    }
  } catch (e, s) {
    print("${e}");
    print("${s}");
  }
}
Enter fullscreen mode Exit fullscreen mode

but, if you want to use this code. you must to know "how to setup this server on you linux".

In this serises, I'll explain about systemd, let's encrypt for dart server.

Environment

ubuntu 20.04
Enter fullscreen mode Exit fullscreen mode

Firewall

First of all. setup a firewall.

$ ufw status
Status: inactive
# $ ufw disable 
$ ufw default deny
$ ufw allow 22/tcp
$ ufw allow 80/tcp
$ ufw allow 443/tcp
$ ufw enable
$ ufw status
Enter fullscreen mode Exit fullscreen mode
  • port 22 is for ssh.you must to allow port 22 if you can access a linux instance to use ssh.

Setup for Systemd

build dart code to native.

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

and create entry shell.

  • ./darthelloserver.sh
#!/bin/sh

#cd /app/hao_dart_server_and_systemd; dart bin/main.dart
/opt/main.exe
Enter fullscreen mode Exit fullscreen mode

and write service setting

  • ./darthelloserver.service
[Unit]
Description=Dart Hello Http Server
After=syslog.target network-online.target

[Service]
ExecStart = /opt/darthelloserver.sh
Restart = always
Type = simple

[Install]
WantedBy=multi-user.target
WantedBy=network-online.target

Enter fullscreen mode Exit fullscreen mode

and regist this service setting to systemd.

$ cp darthelloserver.sh /opt/darthelloserver.sh
$ chmod 655 /opt/darthelloserver.sh
$ cp darthelloserver.service /etc/systemd/system/darthelloserver.service
$ systemctl enable darthelloserver
$ systemctl start darthelloserver
Enter fullscreen mode Exit fullscreen mode

This deamon use systemd-networkd-wait-online.
if systemd-networkd-wait-online is disable status, this deamin didn't run.

you can check like this.

$ systemctl list-unit-files | grep network
$ systemctl enable systemd-networkd
$ systemctl enable systemd-networkd-wait-online
Enter fullscreen mode Exit fullscreen mode

all code

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

Discussion (0)

Forem Open with the Forem app