亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 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 關注
  • 216 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號