Beego アプリを Heroku で動かすための初期設定をご紹介します。
 
beego アプリは bee new しただけの状態です。
ソースコードは GitHub に公開しており、codenote-net/beego-sandbox@9d2a0ea の commit を checkout して heroku へ push すれば動くはずです。
Heroku は PORT が不定なので、process 起動時に環境変数 $PORT を利用する必要があります。
You can refer to your app’s config vars, most usefully $PORT, in the commands you specify.
Heroku 用に $PORT 対応しないと以下のようなエラーが発生してしまいます。
Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
2019-06-04T13:43:30.805065+00:00 heroku[web.1]: State changed from starting to crashed
2019-06-04T13:43:30.821498+00:00 heroku[web.1]: State changed from crashed to starting
2019-06-04T13:43:30.645826+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
2019-06-04T13:43:30.645922+00:00 heroku[web.1]: Stopping process with SIGKILL
2019-06-04T13:43:30.775058+00:00 heroku[web.1]: Process exited with status 137
2019-06-04T13:43:31.427835+00:00 heroku[web.1]: Starting process with command `bin/beego-sandbox`
2019-06-04T13:43:33.934977+00:00 app[web.1]: 2019/06/04 13:43:33.934 [I] [asm_amd64.s:1337]  http server Running on http://:8080
2019-06-04T13:44:20.065228+00:00 heroku[router]: at=error code=H20 desc="App boot timeout" method=GET path="/" host=beego-sandbox.herokuapp.com request_id=38df9122-9d28-46c8-a9f4-22cc76f815b7 fwd="125.197.212.146" dyno= connect= service= status=503 bytes= protocol=https
beego 公式ドキュメントによると Port の設定は beego.BConfig.Listen.HTTPPort, beego.BConfig.Listen.HTTPSPort でそれぞれ行うことができるようです。
HTTPPortSet the port the app listens on. By default this is 8080
beego.BConfig.Listen.HTTPPort = 8080
HTTPSPort
Set the port the app listens on. By default this is 10443
beego.BConfig.Listen.HTTPSPort = 10443
そのため Heroku で beego アプリを動かすためには、以下のように os.Getenv(“PORT”) で環境変数から PORT を取得して beego.BConfig.Listen.HTTPPort, beego.BConfig.Listen.HTTPSPort へそれぞれセットするコードに修正する必要があります。
(サンプルコード) beego for Heroku
package main
import (
  "log"
  "os"
  "strconv"
  "github.com/astaxie/beego"
  _ "github.com/codenote-net/beego-sandbox/routers"
)
func main() {
  log.Println("Env $PORT :", os.Getenv("PORT"))
  if os.Getenv("PORT") != "" {
    port, err := strconv.Atoi(os.Getenv("PORT"))
    if err != nil {
      log.Fatal(err)
      log.Fatal("$PORT must be set")
    }
    log.Println("port : ", port)
    beego.BConfig.Listen.HTTPPort = port
    beego.BConfig.Listen.HTTPSPort = port
  }
  beego.Run()
}
以上、beego アプリを Heroku で動かしたい、現場からお送りしました。