Golang + Gin + Nginx

SELinux

gin

$ vi /path/to/your/project/main.go

main.go

  • ポート番号は適当。ここでは 8080 にする
  • 公式の Quick start をほぼ丸パクリ
package main

import (
	"net/http"

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

func main() {
	r := gin.Default()
	r.GET("/", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"message": "hello, world",
		})
	})
	r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}

Nginx

$ sudo vi /etc/nginx/conf.d/gin-sample.conf

gin-sample.conf

  • gin.sample.com にアクセスすると前提
upstream gin_sample {
   server localhost:8080;
}

server {
    listen       80;
    server_name  gin.sample.com;

    root /path/to/your/project;

    proxy_redirect                          off;
    proxy_set_header Host                   $host;
    proxy_set_header X-Real-IP              $remote_addr;
    proxy_set_header X-Forwarded-Host       $host;
    proxy_set_header X-Forwarded-Server     $host;
    proxy_set_header X-Forwarded-For        $proxy_add_x_forwarded_for;

    location / {
        proxy_pass http://gin_sample/;
    }

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

main.go 起動

$ cd /path/to/your/project
$ go run main.go

もしくは