英文:
How to modify the default port of go gin? My 8080 port is in use
问题
当我使用gin进行测试时,端口无法正常启动:
[ERROR] listen tcp :8080: bind: address already in use
当我使用route来修改端口时,仍然显示8080端口被使用。
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")
}
我应该如何修改它?
英文:
When I use gin to test, the port fails to start normally:
[ERROR] listen tcp :8080: bind: address already in use
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
答案1
得分: 5
你正在调用Run()
两次,而第一次调用没有提供任何地址。因此,在这个实例中使用了默认端口8080。更新代码,在第一次调用中提供地址,并删除重复的调用,这样应该可以解决这个问题。
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
}
}
英文:
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
}
}
答案2
得分: 2
你可以使用环境变量PORT来指定端口,这样在更改部署平台时就不需要修改代码。
例如,使用命令export PORT=8080
来设置端口。
更多信息可以参考gin-gonic/gin的问题405。
英文:
use environment variable PORT. Thus no need to change code if deployment platform change.
eg, export PORT=8080
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论