5

I have developed a rest api using golang.I have pushed the repository to Heroku.I have also hosted a Mysql Server on the internet.The Go rest api connects to the Mysql Server and fetches and inserts data.

The application on heroku was working fine yesterday.However this morning I get this error on "heroku logs --tail": Web process failed to bind to $PORT within 60 seconds of launch

Here is the code for main.go:

package main

import (
    "os"
    "github.com/mingrammer/go-todo-rest-api-example/app"
    "github.com/mingrammer/go-todo-rest-api-example/config"
)

func main() {
    config := config.GetConfig()

    app := &app.App{}
    app.Initialize(config)
    port, ok := os.LookupEnv("PORT")

    if ok == false {
        port = "3000"
    }

    app.Run(":"+port)
}
Jack Gore
  • 3,874
  • 1
  • 23
  • 32
freelancer86
  • 511
  • 2
  • 7
  • 20

4 Answers4

5

You can use os.Getenv for that.

Here is the code for main.go after the modification:

package main

import (
    "os"
    "github.com/mingrammer/go-todo-rest-api-example/app"
    "github.com/mingrammer/go-todo-rest-api-example/config"
)

func main() {
    config := config.GetConfig()

    app := &app.App{}
    app.Initialize(config)
    port, err := os.Getenv("PORT")
    if err != nil {
        port = "3000"
    } 

    app.Run(":"+port)
}
OM Bharatiya
  • 1,840
  • 14
  • 23
0

I solved that using

os.Getenv("PORT")

0

Getenv returns no error.

BAD PRACTIC

port, err := os.Getenv("PORT")
if err != nil {
    port = "3000"
}

GOOD

port := os.Getenv("PORT")
app.Run(":"+port)

DOCUMENTATION GETENV Getenv retrieves the value of the environment variable named by the key. It returns the value, which will be empty if the variable is not present. To distinguish between an empty value and an unset value, use LookupEnv.

-1

This is known issue for node.js apps on Heroku.

In rarer cases, your app may be using process.env.PORT, but may still be failing to bind. This can be caused by the app attempting to bind on localhost. Instead, you may need to change this to 0.0.0.0.

Can assume the same might be an issue for go service as well. Check out this article on Heroku support site .

Vokinneberg
  • 1,912
  • 2
  • 18
  • 31
  • 1
    Very weird stuff, but this actually works! I was developing a restful API with GO gin, and I was getting this error despite having `PORT` in my env. Thanks a ton @Vokinneberg – Prince Singh Oct 09 '22 at 14:17