rest - 使用 Go 向本地主机服务器发出 GET http 请求时的空响应

标签 rest http go docker

我的本​​地主机服务器正在运行,它只是 docker 中的容器进程。我正在尝试实现一个 Go 客户端来构建用于创建、列出、更新、删除功能的 REST api。当我尝试点击 URL 时,程序成功退出但给我一个空响应。我进一步观察到,响应类型是“分 block ”的,内容长度为 -1。我是 Go 的新手,试图弄清楚可能的原因是什么,或者任何人都可以为这个问题提供解决方案。这是我的代码 - {

 package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

type Payload struct {
    Stuff Data
}

type Data struct {
    Id              string
    Links           Links_container
    Actions         Actions_container
    AccountID       string
    AgentID         string
    AllocationState string
    Compute         string
    Created         string
}

type Links_container map[string]string
type Actions_container map[string]string

func main() {
    url := "http://localhost:8080/v1/containers"
    res, err := http.Get(url)
    if err != nil {
        fmt.Println(err)
    }
    defer res.Body.Close()
    body, err := ioutil.ReadAll(res.Body)
    if err != nil {
        fmt.Println(err)
    }

    var p Payload

    err = json.Unmarshal(body, &p)
    if err != nil {
        panic(err)
    }

    fmt.Println(p.Stuff.AccountID, "\n", p.Stuff.Actions, "\n",
        p.Stuff.AgentID, "\n", p.Stuff.AllocationState, "\n", p.Stuff.Compute,
        "\n", p.Stuff.Created, "\n", p.Stuff.Id, "\n", p.Stuff.Links)
}

输出-

map []

map []

这是服务器的 JSON 输出 -

{

"type": "collection",
"resourceType": "container",
"links": {
"self": "…/v1/containers",
},
"createTypes": { },
"actions": { },
"data": [ 2 items
{
"id": "1i2",
"type": "container",
"links": { … },
"actions": { … },
"accountId": "1a1",
"agentId": null,
"allocationState": "active",
"compute": null,
"created": "2014-11-13T23:47:08Z",
"createdTS": 1415922428119,
"data": { … },
"description": null,
"domain": null,
"firstRunning": "2014-11-13T23:49:16Z",
"firstRunningTS": 1415922556030,
"hostname": null,
"imageId": "1i1",
"imageUuid": "docker:dockerfile/ghost:latest",
"instanceTriggeredStop": "stop",
"kind": "container",
"memoryMb": 256,
"name": "dockercontainer",
"primaryAssociatedIpAddress": null,
"primaryIpAddress": "0.0.0.0.",
"removeTime": null,
"removed": null,
"requestedHostId": "1h1",
"startOnCreate": true,
"state": "running",
"token": "xyz",
"transitioning": "no",
"transitioningMessage": null,
"transitioningProgress": null,
"userdata": null,
"uuid": "29614f31-4322-4af4-9a55-d9c9395f5cb7",
"validHostIds": null,
"zoneId": "1z1",
"environment": { },
"command": null,
"commandArgs": [ ],
"directory": null,
"user": null,
"publishAllPorts": false,
"privileged": false,
"dockerVolumes": null,
"ports": [ ],
},
{ … },
],
"sortLinks": { … },
"pagination": { … },
"sort": null,
"filters": { … },
"createDefaults": { },

最佳答案

您需要更改几项才能使其正常工作。

您粘贴的 JSON 无效(使用 linter 检查它)。一旦确定传入的是有效的 JSON,就需要对 go 代码进行如下修改:

  • 需要用选项来“装饰”字段,告诉 JSON 解析器字段名称是什么
  • Payload 结构根据您提供的 JSON 描述包含一段 Data

修改后的代码如下:

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

type Payload struct {
    Stuff []Data `json:"data"`
}

type Data struct {
    Id              string            `json:"id"`
    Links           Links_container   `json:"links"`
    Actions         Actions_container `json:"actions"`
    AccountID       string            `json:"accountId"`
    AgentID         string            `json:"agentId"`
    AllocationState string            `json:"allocationState"`
    Compute         string            `json:"compute"`
    Created         string            `json:"created"`
}

type Links_container map[string]string
type Actions_container map[string]string

func main() {
    url := "http://localhost:8080/v1/containers"
    res, err := http.Get(url)
    if err != nil {
        fmt.Println(err)
    }
    defer res.Body.Close()
    body, err := ioutil.ReadAll(res.Body)
    if err != nil {
        fmt.Println(err)
    }

    var p Payload

    err = json.Unmarshal(body, &p)
    if err != nil {
        panic(err)
    }

    for _, stuff := range p.Stuff {
        fmt.Println(stuff.AccountID, "\n", stuff.Actions, "\n",
            stuff.AgentID, "\n", stuff.AllocationState, "\n", stuff.Compute,
            "\n", stuff.Created, "\n", stuff.Id, "\n", stuff.Links)
    }
}

这里有 a working version in the sandbox

关于rest - 使用 Go 向本地主机服务器发出 GET http 请求时的空响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26943619/

相关文章:

go - 如何处理 gorp Select 中的空值

python - 使用 Django Rest Framework 时如何访问请求正文并避免获取 RawPostDataException

go - 返回 Golang 中的 CPU 插槽数、核心数和线程数

mysql - 如何从 MySQL 中选择数据然后将其附加到新结构并将其转换为字节

java - HttpCore 用于测量 http 请求/响应耗时

http - 是否可以验证 GET 是来自按钮还是输入 URL 栏?

.net - 企业服务器 WCF 压力/线束测试

php - Stripe 签账卡使用 php Rest api 时出现 fatal error

android - 即使按照实际程序也无法解析android中的json数据

api - 良好做法 : REST API as the interface between the interface layer and business layer?