LoginSignup
0
0

More than 3 years have passed since last update.

goLang+gin+nginxで開発環境を作ってみる

Last updated at Posted at 2021-04-08

目的

GoLang + Gin の開発環境をWindows(Vagrant-AmazonLinux2)で試してみる

環境

  • OS:Windows10Pro
  • VM:Vagrant(AmazonLinux2)
  • BackEnd:Go + Gin

VM設定

Vagrantで開発環境作ります。

1.ローカル環境に任意のフォルダ(c/venv/xxxx-apl)を作成する。
2.Vagrant定義(bash起動して下記コマンド実行)

cd /c/venv/xxxx-apl
vagrant init gbailey/amzn2

3.Vagrantファイルの作成(C:\venv\xxxx-apl\Vagrantfile)

Vagrant.configure("2") do |config|
# AmazonLinux2
  config.vm.box = "gbailey/amzn2"
  config.vm.network "private_network", ip: "192.168.33.10"
# ローカル開発環境(c:\gits\xxxx-apl)とホストのappディレクトリを同期する
  config.vm.synced_folder "/gits/xxxx-apl", "/app/xxxx-apl",type: "virtualbox"
end

4.Vagrant 起動

vagrant up

GoLang

Goをインストールします。

1.yum update

sudo yum update

2.Install Golang

sudo yum install -y golang

AmazonLinux2extraの方がバージョンが低かったのでそのままyumで入れました

Gomod

Goのモジュール管理(Gomod)を設定します。

1.envのGoModuleを有効化します

cd /app/xxxx-apl
go env -w GO111MODULE=on

2.gomodの初期化を行います

go mod init xxxx-apl

Gin

GoLangのwebフレームワークGinを入れます。

go get -u github.com/gin-gonic/gin

Nginx

WebServerはNginxを利用します。

1.extrasからnginxをインストール

sudo amazon-linux-extras install nginx1

2.nginx起動

sudo systemctl start nginx

3.nginxの自動起動設定を行う

sudo systemctl enable nginx

4.ブラウザで確認(Vagrantに設定したIPでアクセス)

http://192.168.33.10/

試してみる

  1. main.goを作成
package main

import "github.com/gin-gonic/gin"

func main() {
    r := gin.Default()
    r.GET("/api/test", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "message": "hellow!",
        })
    })
    r.Run() // listen and serve on 0.0.0.0:8080
}

2.nginx設定
/etc/nginx/xxxx-apl.confを作成し配置

server  {
     listen       80;
     location / {
         proxy_pass http://127.0.0.1:8080;
     }
    error_log  /var/log/nginx/xxxx-apl.error.log error;
}

3.起動

go run main.go

4.ブラウザアクセスhttp://192.168.30.10/api/testして下記が表示される

"message": "hellow!"
0
0
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
0
0