systemd socket activation golang demo
service define
rongapp.service
[Unit]
Description=rong Hello World HTTP
Requires=network.target rongapp.socket
After=multi-user.target
[Service]
Type=simple
ExecStart=/usr/bin/rong
[Install]
WantedBy=multi-user.target
socket define
[Socket]
ListenStream=8076
Accept=yes
[Install]
WantedBy=sockets.target
main.go
package main
import (
"io"
"net/http"
"github.com/coreos/go-systemd/activation"
)
func HelloServer(w http.ResponseWriter, req *http.Request) {
io.WriteString(w, "hello socket activated world!\n")
}
func main() {
listeners, err := activation.Listeners()
if err != nil {
panic(err)
}
if len(listeners) != 1 {
panic("Unexpected number of socket activation fds")
}
http.HandleFunc("/", HelloServer)
http.Serve(listeners[0], nil)
}
go mod
go mod init github.com/rongfengliang/appdemo
gp get github.com/coreos/go-systemd/activation
start service
- copy define files
location /usr/lib/systemd/system/
- start socket
systemctl start rongapp.socket
systemctl start rongapp.service
systemctl enable rongapp.socket
systemctl enable rongapp.service
test
curl http://127.0.0.1:8076
some links
https://github.com/coreos/go-systemd/tree/master/examples/activation/httpserver