在使用Go语言向本地服务器发出GET HTTP请求时,返回了空响应。

huangapple go评论88阅读模式
英文:

Empty response while making a GET http request to the localhost server using Go

问题

我有一个正在运行的本地服务器,实际上就是一个在Docker中的容器进程。我正在尝试实现一个Go客户端来构建用于创建、列出、更新和删除功能的REST API。当我尝试访问URL时,程序成功退出,但是返回了一个空响应。进一步观察,我发现响应类型是"chunked",内容长度为-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": [
        {
            "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": {}
}

希望对你有帮助!

英文:

I have my localhost server running which is nothing but the container process in a docker.I am trying to implement a Go CLIENT to build REST api's for Create, List, Update, Delete functionalities. When I try to hit the URL, the program exits successfully but gives me an empty response. Further I observed, that the response type is "chunked" with the content length as -1. I am new to Go and trying to figure out what could be the possible reasons or could anyone provide a solution to this problem. Here it my code -
{

 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)
}

}

Output-

map[]

map[]

This is the JSON output from the server -

{

"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": { },

}

答案1

得分: 2

有几个需要更改的地方才能使其正常工作。

你粘贴的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)
	}
}

你可以在sandbox中找到一个可工作的版本

英文:

There are several things that you need to change to make it work.

The JSON you pasted is not valid (check on it with a linter). Once you are sure that what is coming in is valid JSON, the go code needs to be modified as follows:

  • Fields need to be "decorated" with options that tell the JSON parser what the field names are
  • The Payload struct contains a slice of Data based on the JSON description you provided

The modified code would look then:

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)
}
}

Here you have a working version in the sandbox

huangapple
  • 本文由 发表于 2014年11月15日 15:23:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/26943619.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定