Go Echoで書いたREST APIサーバーをHerokuにDeployする

Web開発

Herokuはデプロイ作業の手軽さから本番環境はもちろんのことデバッグ用にテストサーバーを立てたい時に最適です。

今回は単純にHello, World!を表示するだけの簡単なGoサーバーを立ててみます。下のEchoのサンプルコードをmain.goに追加します。

package main

import (
	"net/http"

	"github.com/labstack/echo/v4"
)

func main() {
	e := echo.New()
	e.GET("/", func(c echo.Context) error {
		return c.String(http.StatusOK, "Hello, World!")
	})
	e.Logger.Fatal(e.Start(":5000"))
}

次にコンパイルするための準備としてパッケージをダウンロードします。ここではGo Moduleを使うためgo mod initでgo.modファイルを作成します。

go mod init echo-sample

その後、go buildコマンドでecho-sampleと言う実行ファイルが出力されました。

Hello, worldプログラム自体は完成しましたがHeroku上でListenするポート に対応するため一つだけ関数を追加します。

package main

import (
	"net/http"
	"os"

	"github.com/labstack/echo/v4"
)

// この関数を追加
func port() string {

	port := os.Getenv("PORT")

	if len(port) == 0 {
		port = "8080"
	}

	return ":" + port
}

func main() {
	e := echo.New()
	e.GET("/", func(c echo.Context) error {
		return c.String(http.StatusOK, "Hello, World!")
	})
     
     // Port番号を関数から取得
	e.Logger.Fatal(e.Start(port()))
}

HerokuのDeployの準備に入る前にGitリポジトリのイニシャライズとコミットを行っておきます。

git init
git add .
git commit -m "first commit"

Procfileの作成

Procfileで起動する実行ファイルを指定します。

web: main

このプロジェクトの場合go buildで出力される実行バイナリがmainになりますので、上のような記述になります。もし、serverであればここをserverのように任意に変更してください。

Herokuアプリの作成

次にHerokuのアプリを作成します。こちらはWebサイトからも可能ですが今回はコマンドラインで作成をします。heroku create以降に好きなアプリ名を入力して簡単に作成できます。また、この文字列はURLにもなります。この場合ですと、https://go-rest-api-r01.herokuapp.comとなります。

heroku create go-rest-api-r01

HerokuへDeploy

git push heroku masterコマンドを実行しHeroku GitにPushするだけでDeployができます。GitのLogにDeployの経過と結果がログ出力されるので確認しましょう。

remote: Verifying deploy… done.と表示されていればDeployが成功です。そうでない場合はビルドやコンパイルなど何かしらのエラーが発生しています。

Enumerating objects: 6, done.
Counting objects: 100% (6/6), done.
Delta compression using up to 4 threads
Compressing objects: 100% (5/5), done.
Writing objects: 100% (6/6), 3.08 KiB | 1.54 MiB/s, done.
Total 6 (delta 0), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote: 
remote: -----> Go app detected
remote: -----> Fetching jq... done
remote: -----> Fetching stdlib.sh.v8... done
remote: -----> 
remote:        Detected go modules via go.mod
remote: -----> 
remote:        Detected Module Name: echo-sample
remote: -----> 
remote:  !!    The go.mod file for this project does not specify a Go version
remote:  !!    
remote:  !!    Defaulting to go1.12.17
remote:  !!    
remote:  !!    For more details see: https://devcenter.heroku.com/articles/go-apps-with-modules#build-configuration
remote:  !!    
remote: -----> New Go Version, clearing old cache
remote: -----> Installing go1.12.17
remote: -----> Fetching go1.12.17.linux-amd64.tar.gz... done
remote: -----> Determining packages to install
remote:        
remote:        Detected the following main packages to install:
remote:                 echo-sample
remote:        
remote: -----> Running: go install -v -tags heroku echo-sample 
remote: golang.org/x/sys/unix
remote: github.com/valyala/bytebufferpool
remote: github.com/valyala/fasttemplate
remote: golang.org/x/crypto/acme
remote: golang.org/x/text/transform
remote: golang.org/x/text/unicode/bidi
remote: golang.org/x/text/secure/bidirule
remote: github.com/mattn/go-isatty
remote: golang.org/x/text/unicode/norm
remote: github.com/mattn/go-colorable
remote: github.com/labstack/gommon/color
remote: github.com/labstack/gommon/log
remote: golang.org/x/net/http2/hpack
remote: golang.org/x/net/idna
remote: golang.org/x/net/http/httpguts
remote: golang.org/x/crypto/acme/autocert
remote: golang.org/x/net/http2
remote: golang.org/x/net/http2/h2c
remote: github.com/labstack/echo/v4
remote: echo-sample
remote:        
remote:        Installed the following binaries:
remote:                 ./bin/echo-sample
remote: -----> Discovering process types
remote:        Procfile declares types -> web
remote: 
remote: -----> Compressing...
remote:        Done: 4.2M
remote: -----> Launching...
remote:        Released v3
remote:        https://go-rest-api-r01.herokuapp.com/ deployed to Heroku
remote: 
remote: Verifying deploy... done.
To https://git.heroku.com/go-rest-api-r01.git
 * [new branch]      master -> master

URLにアクセスして確認

Deployが成功したらしっかりと動作するか確認します。下のようなHerokuのエラー画面が表示される場合はデーターベースの環境変数をセットしていないなどなんらかのエラーが発生している可能性があります。その場合はheroku logs –tailで詳細なログを取得して解決しましょう。

Hello Tシャツ C言語

Hello, world!プログラムのTシャツ。こちらはC言語で書かれたバージョンです。

コメント

タイトルとURLをコピーしました