Google App Engine:Api Page not found after deployment

Viewed 231

Using Golang, I wrote this basic server:

func main() {

    router := gin.Default()
    router.GET("/api", func(c *gin.Context) {
        c.JSON(http.StatusOK, gin.H{"data": "hello world"})
    })

    router.LoadHTMLGlob("www/*.html")
    router.GET("/", func(c *gin.Context) {
        c.HTML(http.StatusOK, "index.html", nil)
    })

    fmt.Println("listening on localhost:8080")

    router.Run("localhost:8080")

}

It works fine running on localhost.

After I deploy with sudo gcloud app deploy, I browse to the hosting url route for the main page and with static files works fine, but when I browse to /api route it throws Page not found error (which works locally)

Here is the app.yaml used for deploying to App Engine:

runtime: go116

handlers:
- url: /
  static_files: www/index.html
  upload: www/index.html

- url: /(.*)
  static_files: www/\1
  upload: www/(.*)

What I have tried:

What am I doing wrong here?

Note: The Go version I run on localhost is 1.17 but App Engine supports up to version 1.15

1 Answers

From the test I made, I would suggest to use the scripts handler element in your app.yaml as stated in the documentation, like this:

runtime: go115

handlers:
- url: /(.*)
  script: auto

This way, your Go router will serve all your traffic, as stated by the documentation:

The only accepted value for the script element is auto because all traffic is served using the entrypoint command.

Also, I would suggest to change your last line in your code to:

router.Run()

As pointed in this issue on GitHub:

... no parameter: router.Run()
Under this API, gin will try to read the PORT environment variable and use it.
If the PORT variable is not defined, ":8080" would be used by default.

This advice came after checking the logs on the test deploy I made:

App is listening on port 8080. We recommend your app listen on the port defined by the PORT environment variable to take advantage of an NGINX layer on port 8080

For further debugging in your app, I would recommend checking the Viewing logs documentation.

Related