Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify the default port of go gin? My 8080 port is in use

Tags:

go

When I use gin to test, the port fails to start normally: [ERROR] listen tcp :8080: bind: address already in use enter image description here When I use the route to modify the port, it still shows that 8080 port is used


func main() {
  //r := gin.Default()
  //r.GET("/ping", func(c *gin.Context) {
  //  c.JSON(http.StatusOK, gin.H{
  //    "message": "pong",
  //  })
  //})
  router := gin.Default()
    router.GET("/hi", func(context *gin.Context) {
        context.String(http.StatusOK, "Hello world!")
    })
    err := router.Run()
    if err != nil {
        panic("[Error] failed to start Gin server due to: " + err.Error())
        return
    }
  router.Run(":9888")
  //r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}

How should I modify it

like image 985
zero20210602 Avatar asked Oct 18 '25 09:10

zero20210602


2 Answers

You're calling Run() twice - and the first instance is being called without any address being supplied. So the default port 8080 is being used in this instance. Updating the code to supply the address in the first call, and removing the duplicate call should hopefully resolve this for you.

func main() {
    router := gin.Default()
    router.GET("/hi", func(context *gin.Context) {
        context.String(http.StatusOK, "Hello world!")
    })
    err := router.Run(":9888")
    if err != nil {
        panic("[Error] failed to start Gin server due to: " + err.Error())
        return
    }
}
like image 60
nj_ Avatar answered Oct 20 '25 22:10

nj_


use environment variable PORT. Thus no need to change code if deployment platform change.

eg, export PORT=8080

gin-gonic/gin/issues/405

like image 30
qeatzy Avatar answered Oct 20 '25 22:10

qeatzy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!