Goをインストールする
# cat /etc/lsb-release DISTRIB_ID=Ubuntu DISTRIB_RELEASE=18.04 DISTRIB_CODENAME=bionic DISTRIB_DESCRIPTION="Ubuntu 18.04.6 LTS" # whoami root # cd /usr/local/src/ # wget https://go.dev/dl/go1.18.4.linux-amd64.tar.gz # tar -C /usr/local -xzf go1.18.4.linux-amd64.tar.gz # echo 'export GOROOT=/usr/local/go' >> ~/.profile # echo 'export PATH=$PATH:$GOROOT/bin' >> ~/.profile # source ~/.profile # go version go version go1.18.4 linux/amd64
systemdへ登録して9990ポートで閲覧できるようにする
# cd /var/www/akat.info/mgt/htdocs # vi main.go package main import ( "fmt" "net/http" ) func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello World") }) http.HandleFunc("/greet/", func(w http.ResponseWriter, r *http.Request) { name := r.URL.Path[len("/greet/"):] fmt.Fprintf(w, "Hello %s\n", name) }) http.ListenAndServe(":9990", nil) } # go build main.go # vi /lib/systemd/system/goweb.service [Unit] Description=goweb [Service] Type=simple Restart=always RestartSec=5s ExecStart=/var/www/akat.info/mgt/htdocs/main [Install] WantedBy=multi-user.target # systemctl daemon-reload # systemctl start goweb # systemctl status goweb ● goweb.service - goweb Loaded: loaded (/lib/systemd/system/goweb.service; disabled; vendor preset: enabled) Active: active (running) since Sun 2022-07-31 22:52:48 JST; 5s ago Main PID: 9045 (main) Tasks: 4 (limit: 1152) CGroup: /system.slice/goweb.service └─9045 /var/www/akat.info/mgt/htdocs/main 7月 31 22:52:48 tech systemd[1]: Started goweb. # curl http://localhost:9990 Hello World
Nginxと連携させる
Nginxの設定に以下を追加して、Nginxを再起動する。
... location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_pass http://127.0.0.1:9990; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_next_upstream error timeout http_502 http_503 http_504; } ...
参考
https://quicknotepadtutorial.blogspot.com/2019/09/how-to-setup-go-web-application-using.html