2018-10-29 22:14
浏览 174


So I am currently working on building a restful api in go using the gin-gonic package. I hope to deploy the code to a google cloud platform compute engine VM. When I run the code on my local machine it works with using local host but when running it on the actual VM instance with the external IP specified I get a bind error with the TCP connection. Any help appreciated.


package main

import (


type headlines struct {
    Author      string
    Title       string
    Description string
    Url         string
    UrlToImage  string
    PublishedAt string
    Content     string

type NewsResponse struct {
    Status       string
    TotalResults int
    Articles     []headlines

func GetSourceHeadlines(source string) NewsResponse {
    newsAPIKey := os.Getenv("NEWS_API_KEY")
    var newsResponse NewsResponse
    resp, err := http.Get("" + source + "&apiKey=" + newsAPIKey)

    if err != nil {

    defer resp.Body.Close()

    if resp.StatusCode == http.StatusOK {
        bodyBytes, _ := ioutil.ReadAll(resp.Body)
        err := json.Unmarshal(bodyBytes, &newsResponse)
        if err == nil {
            return newsResponse
    return newsResponse

func main() {
    r := gin.Default()
    r.GET("/headlines/ign", func(c *gin.Context) {
        c.JSON(http.StatusOK, GetSourceHeadlines("ign"))

    r.GET("/headlines/polygon", func(c *gin.Context) {
        c.JSON(http.StatusOK, GetSourceHeadlines("polygon"))

    r.GET("/headlines/techcrunch", func(c *gin.Context) {
        c.JSON(http.StatusOK, GetSourceHeadlines("techcrunch"))

    r.GET("/headlines/hacker-news", func(c *gin.Context) {
        c.JSON(http.StatusOK, GetSourceHeadlines("hacker-news"))


[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.

[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
 - using env:   export GIN_MODE=release
 - using code:  gin.SetMode(gin.ReleaseMode)

[GIN-debug] GET    /headlines/ign            --> main.main.func1 (3 handlers)
[GIN-debug] GET    /headlines/polygon        --> main.main.func2 (3 handlers)
[GIN-debug] GET    /headlines/techcrunch     --> main.main.func3 (3 handlers)
[GIN-debug] Listening and serving HTTP on
[GIN-debug] [ERROR] listen tcp bind: cannot assign requested address
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duanping2695 2018-10-30 07:44

    You can only listen localhost, then access via your host's ip, like


 is not necessary.

    解决 无用
    打赏 举报
  • dongquweng5152 2018-10-30 00:37

    You need to use instead of what you are currently using on .Run() statement. By using, the server will be accessible from available network interface.


    So accessing from external IP will points towards your app.

    解决 无用
    打赏 举报

相关推荐 更多相似问题