Dart HttpServer & Systemd
kyorohiro (kiyohiro kawamura)
Posted on April 3, 2021
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}");
}
}
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
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
- 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
and create entry shell.
- ./darthelloserver.sh
#!/bin/sh
#cd /app/hao_dart_server_and_systemd; dart bin/main.dart
/opt/main.exe
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
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
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
all code
https://github.com/kyorohiro/hao_dart_server_and_systemd/tree/dev01
💖 💪 🙅 🚩
kyorohiro (kiyohiro kawamura)
Posted on April 3, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.