LoginSignup
7
1

More than 3 years have passed since last update.

Goで簡単なHTTPサーバーとSystemdの自動起動の設定

Posted at

本ページではGoで簡単なHTTPサーバのコードを掲載し、systemdでLinux(Ubuntu, Archlinux)のサービスのプログラムの自動起動を行います。

Goで簡単なHTTPサーバのコード

$ pwd
$HOME/go/src/SimpleHttp

$ cat SimpleHttp.go
package main

import (
        "fmt"
        "net/http"
)

func SimpleHttpHandler(w http.ResponseWriter, r *http.Request) {
        fmt.Fprint(w, "Simple HTTPサーバー & Systemd Serviceの設置")
}

func main() {
        http.HandleFunc("/", SimpleHttpHandler)

        // 8080ポートで起動
        http.ListenAndServe(":8080", nil)
}

SimpleHttpのビルド

$ pwd
$HOME/go/src/SimpleHttp

$ tree
.
└── SimpleHttp.go

0 directories, 1 file

$ go build SimpleHttp.go

$ tree
.
├── SimpleHttp
└── SimpleHttp.go

0 directories, 2 files

ユニットファイルSimpleHttp.serviceの内容

$ cat /lib/systemd/system/SimpleHttp.service 
[Unit]
Description = SimpleHttp.service daemon

[Service]
Environment="GOPATH=$HOME/go"
ExecStart=$HOME/go/src/SimpleHttp/SimpleHttp
Restart=always
Type=simple
User=ubuntu
Group=ubuntu
# Other directives omitted
# (file size)
LimitFSIZE=infinity
# (cpu time)
LimitCPU=infinity
# (virtual memory size)
LimitAS=infinity
# (open files)
LimitNOFILE=64000
# (processes/threads)
LimitNPROC=64000

[Install]
WantedBy = multi-user.target

SimpleHttpサービスのリロード

新規のユニットファイルSimpleHttp.serviceの作成または変更後に常に以下のコマンドを実行します。

sudo systemctl daemon-reload

SimpleHttpサービスの有効

$ sudo systemctl enable SimpleHttp.service

SimpleHttpサービスの起動

$ sudo systemctl start SimpleHttp.service

SimpleHttpサービスの停止

sudo systemctl stop SimpleHttp.service

SimpleHttpサービスの無効化

$ sudo systemctl disable SimpleHttp.service

ArchLinuxのバージョンの確認

$ uname -a
Linux arch.local 5.6.10-arch1-1 #1 SMP PREEMPT Sat, 02 May 2020 19:11:54 +0000 x86_64 GNU/Linux

$ lsb_release -a
LSB Version:    1.4
Distributor ID: Arch
Description:    Arch Linux
Release:    rolling
Codename:   n/a

Ubuntuのバージョンの確認

$ uname -a
Linux ip-172-31-8-186 5.3.0-1017-aws #18~18.04.1-Ubuntu SMP Wed Apr 8 15:12:16 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux

$ cat /etc/lsb-release 
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=18.04
DISTRIB_CODENAME=bionic
DISTRIB_DESCRIPTION="Ubuntu 18.04.4 LTS"

$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 18.04.4 LTS
Release:    18.04
Codename:   bionic
7
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
1