当我使用gin测试时,端口无法正常启动:[ERROR]listen tcp :8080:bind:address already in use
当我使用路由修改端口时,仍然显示使用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")
}
Run Code Online (Sandbox Code Playgroud)
我应该如何修改它
您调用了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
}
}
Run Code Online (Sandbox Code Playgroud)