为了账号安全,请及时绑定邮箱和手机立即绑定

使用 Golang + Gin + Docker 时出现“localhost 没有发送任何数据”

使用 Golang + Gin + Docker 时出现“localhost 没有发送任何数据”

Go
慕田峪7331174 2022-11-28 10:37:48
我已经按照在本地完美运行的 youtube 教程创建了一个简单的 API。将应用程序容器化并运行容器后,我无法访问 http://localhost:8080 上的 API。我猜它与我在 dockerfile 中使用的端口设置有关,但我不确定。main.go 文件:package mainimport (    "net/http"    "github.com/gin-gonic/gin"    "errors")type phone struct{    ID       string `json:"id"`    Model    string `json:"model"`    Year     string `json:"year"`    Quantity int    `json:"quantity"`}var phones = []phone{    {ID: "1", Model: "iPhone 11", Year: "2019", Quantity: 4},    {ID: "2", Model: "iPhone 6", Year: "2014", Quantity: 9},    {ID: "3", Model: "iPhone X", Year: "2017", Quantity: 2},}func phoneById(c *gin.Context) {    id := c.Param("id")    phone, err := getPhoneById(id)    if err != nil {        c.IndentedJSON(http.StatusNotFound, gin.H{"message": "Phone not found."})        return    }    c.IndentedJSON(http.StatusOK, phone)}func checkoutPhone(c *gin.Context) {    id, ok := c.GetQuery("id")    if !ok {        c.IndentedJSON(http.StatusBadRequest, gin.H{"Message": "Missing id query paramater"})        return    }    phone, err := getPhoneById(id)    if err != nil {        c.IndentedJSON(http.StatusBadRequest, gin.H{"Message": "Phone not found"})        return    }    if phone.Quantity <= 0 {        c.IndentedJSON(http.StatusBadRequest, gin.H{"Message": "Phone not available."})        return    }    phone.Quantity -= 1    c.IndentedJSON(http.StatusOK, phone)}func returnPhone(c *gin.Context) {    id, ok := c.GetQuery("id")    if !ok {        c.IndentedJSON(http.StatusBadRequest, gin.H{"Message": "Missing id query paramater"})        return    }    phone, err := getPhoneById(id)    if err != nil {        c.IndentedJSON(http.StatusBadRequest, gin.H{"Message": "Phone not found"})        return    }    if phone.Quantity <= 0 {        c.IndentedJSON(http.StatusBadRequest, gin.H{"Message": "Phone not available."})        return    }    phone.Quantity += 1    c.IndentedJSON(http.StatusOK, phone)}
查看完整描述

1 回答

?
尚方宝剑之说

TA贡献1788条经验 获得超4个赞

您需要绑定到容器内部的公共网络接口。因为每个容器都是自己的host,当你在里面绑定loopback接口的时候,外界就访问不到了。

router.Run("0.0.0.0:8080")

此外,确保在运行容器时发布此端口。

docker run --publish 8080:8080 myapp

你实际上用你的环境变量表明了正确的意图,但它们没有在你的代码中使用。

ENV HOST 0.0.0.0
ENV PORT 8080

您可以使用os.Getenvos.LookupEnv从您的代码中获取这些变量并使用它们。


查看完整回答
反对 回复 2022-11-28
  • 1 回答
  • 0 关注
  • 215 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号