Description

gin keeps starting on port 3000 even when I have port 8080 in the env file or if I do GIN_MODE=debug PORT=8080 gin run main.go

How to reproduce

package main

import (
    "github.com/gin-gonic/gin"
    "github.com/irohitb/EmpAdmin/backend/config"
    route "github.com/irohitb/EmpAdmin/backend/routes"
)

func main() {
    app := config.App()
    env := app.Env
    gin := gin.Default()
    gin.Use(CORSMiddleware())
    db := app.Db
    route.Setup(env,db, gin)
    gin.Run(":" + env.Port)
}

Where env.Port is 8080.

To run I do GIN_MODE=debug PORT=8080 gin run main.go

Expectations

It should've run on Port 8080

Actual result

It runs on Port 3000,

Also a video: https://drive.google.com/file/d/12ipP-mTiFGu9KYBwV_iY_WbNDypEANEX/view?usp=sharing

Environment

  • go version: go version go1.20.3 darwin/arm64
  • gin version (or commit ref): github.com/gin-gonic/gin v1.9.0
  • operating system: MacOsx

Comment From: pscheid92

When you set an address via gin.Run(":" + env.Port), gin ignores the PORT environment variable.

https://github.com/gin-gonic/gin/blob/eac2daac64811197970b5d2f6406e4ae6c31cb5e/gin.go#L376-L388

https://github.com/gin-gonic/gin/blob/eac2daac64811197970b5d2f6406e4ae6c31cb5e/utils.go#L140-L154

Therefore, I guess something is wrong with your code in github.com/irohitb/EmpAdmin/backend/config, which isn't public. Nor is your video working anymore.

Comment From: snowdream

package main

import (
    "github.com/gin-gonic/gin"
    "github.com/irohitb/EmpAdmin/backend/config"
    route "github.com/irohitb/EmpAdmin/backend/routes"
)

func main() {
    app := config.App()
    env := app.Env
    gin := gin.Default()
    gin.Use(CORSMiddleware())
    db := app.Db
    route.Setup(env,db, gin)
    gin.Run()
}

Then :

GIN_MODE=debug PORT=8080 gin run main.go

Comment From: danielkperez

Interesting. I have used the following since, as seen in Gin's source code, users can pass a port to the Run function.

Gin App.Run()

// Run attaches the router to a http.Server and starts listening and serving HTTP requests.
// It is a shortcut for http.ListenAndServe(addr, router)
// Note: this method will block the calling goroutine indefinitely unless an error happens.
func (engine *Engine) Run(addr ...string) (err error) {
    defer func() { debugPrintError(err) }()

    if engine.isUnsafeTrustedProxies() {
        debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" +
            "Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.")
    }

    address := resolveAddress(addr)
    debugPrint("Listening and serving HTTP on %s\n", address)
    err = http.ListenAndServe(address, engine.Handler())
    return
}

Implementation

package main

import (
    "os"
    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.Default()
    r.GET("/ping", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "message": "pong",
        })
    })
        port := ":" + os.Getenv("APP_PORT")
    r.Run(port) // listen and serve on 0.0.0.0:8080
}

.env

APP_PORT=3000

Comment From: irohitb

@pscheid92

This is my config.go file (video should also be working now)

package config

import (
    "log"

    "github.com/spf13/viper"
)

type Env struct {
  AppEnv                string `mapstructure:"APP_ENV"`
  Port                  string `mapstructure:"PORT"`
  Host                  string `mapstructure:"HOST"`
  SupabaseJwtSecret     string `mapstructure:"SUPABASE_JWT_SECRET"`
  SupabaseUrl           string `mapstructure:"SUPABASE_URL"`
  FrontendErrorUrl string
  FrontendServicesCb string
}


func NewEnv() *Env  {
    env := Env{}
    viper.SetConfigFile(".env")

    err := viper.ReadInConfig()
    if err != nil {
        log.Fatal("Can't find the file .env : ", err)
    }

    err = viper.Unmarshal(&env)
    if err != nil {
        log.Fatal("Environment can't be loaded: ", err)
    }

    if env.AppEnv == "development" {
        log.Println("The App is running in development env")
    }

  env.FrontendErrorUrl = env.FrontendUrl + "/error"
  env.FrontendServicesCb = env.FrontendUrl + "/services/callback"


    return &env
}

Comment From: pscheid92

@irohitb I was able to open your screen recoding now. You are running a CLI tool named gin where I would have expected go. Can you tell me which CLI tool that is?

You are running gin run main.go but I would expect go run main.go.

EDIT: Is it this one? https://github.com/codegangsta/gin Could you try starting without go run main.go?

Comment From: irohitb

@pscheid92 yap, with go run main.go the code works fine but I also need hot reload. I have been using go run main.go till now

Yap this the one: https://github.com/codegangsta/gin

Comment From: irohitb

I think I have opened issue in the wrong repo, closing this one.