我已經(jīng)按照在本地完美運(yùn)行的 youtube 教程創(chuàng)建了一個(gè)簡(jiǎn)單的 API。將應(yīng)用程序容器化并運(yùn)行容器后,我無(wú)法訪問(wèn) http://localhost:8080 上的 API。我猜它與我在 dockerfile 中使用的端口設(shè)置有關(guān),但我不確定。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)}
使用 Golang + Gin + Docker 時(shí)出現(xiàn)“localhost 沒(méi)有發(fā)送任何數(shù)據(jù)”
慕田峪7331174
2022-11-28 10:37:48