英文:
Unable to access Go server when hosted on AWS
问题
我已经用gin在Go中创建了一个项目,并且在本地运行正常。但是,当我尝试在AWS的EC2实例上部署时,无法访问服务器上的API。
我通过ssh登录到托管的机器上,并发送了一个curl请求(curl localhost:8080
),它返回了正确的响应。但是,来自外部的任何请求都无法访问。
服务器正在8080端口上运行。我已经在AWS安全组中打开了这些端口。
在Go/gin中是否有任何设置需要进行,以便从互联网上访问它?
示例代码:
package main
import (
"myConstants"
"myDatabase"
"myMiddleware"
"onboarding"
"github.com/gin-gonic/gin"
)
func main() {
var db = myDatabase.DBConnect()
router := gin.Default()
router.Use(myMiddleware.RestrictInputContent)
router.Use(myMiddleware.CheckToken(db))
router.Use(myMiddleware.RequestLoggerMiddleware())
router.POST("/signup", onboarding.Signup(db))
router.POST("/login", onboarding.Login(db))
router.POST("/logout", onboarding.Logout(db))
router.GET("/", onboarding.Hello(db))
defer db.Close()
//Listen and serve
router.Run("127.0.0.1:8080")
}
英文:
I have created a project in Go using gin and it is working fine locally. However, when I tried deploying this on an EC2 instance on AWS, I was unable to access the APIs on the server.
I did a ssh into the hosted machine and gave a curl request (curl localhost:8080
) and it gave a proper response. But any request from outside is not reachable.
The server is running on port 8080. I have opened the ports in the AWS security groups.
Is there any setting in Go/gin that I need to make for it to be accessible from the internet?
Sample code:
package main
import (
"myConstants"
"myDatabase"
"myMiddleware"
"onboarding"
"github.com/gin-gonic/gin"
)
func main() {
var db = myDatabase.DBConnect()
router := gin.Default()
router.Use(myMiddleware.RestrictInputContent)
router.Use(myMiddleware.CheckToken(db))
router.Use(myMiddleware.RequestLoggerMiddleware())
router.POST("/signup", onboarding.Signup(db))
router.POST("/login", onboarding.Login(db))
router.POST("/logout", onboarding.Logout(db))
router.GET("/", onboarding.Hello(db))
defer db.Close()
//Listen and serve
router.Run("127.0.0.1:8080")
}
答案1
得分: 10
将router.Run("127.0.0.1:8080")
更改为router.Run(":8080")
,然后它就可以工作了。
如@elithrar和@user3591723建议的那样。
127.0.0.1(本地主机)只是机器上的回环接口。
绑定到":8080"意味着0.0.0.0:8080 - 这意味着所有接口。
英文:
Changed the router.Run from router.Run("127.0.0.1:8080")
to router.Run(":8080")
and it works.
As suggested by @elithrar and @user3591723
127.0.0.1 (local host) is only the loop back interface on the machine
Binding to ":8080" means 0.0.0.0:8080 - which means all interfaces
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论