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

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

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

问题

我有一个正在运行的本地服务器,实际上就是一个在Docker中的容器进程。我正在尝试实现一个Go客户端来构建用于创建、列出、更新和删除功能的REST API。当我尝试访问URL时,程序成功退出,但是返回了一个空响应。进一步观察,我发现响应类型是"chunked",内容长度为-1。我对Go还不熟悉,正在努力找出可能的原因,或者是否有人能提供解决这个问题的解决方案。以下是我的代码:

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. )
  8. type Payload struct {
  9. Stuff Data
  10. }
  11. type Data struct {
  12. Id string
  13. Links Links_container
  14. Actions Actions_container
  15. AccountID string
  16. AgentID string
  17. AllocationState string
  18. Compute string
  19. Created string
  20. }
  21. type Links_container map[string]string
  22. type Actions_container map[string]string
  23. func main() {
  24. url := "http://localhost:8080/v1/containers"
  25. res, err := http.Get(url)
  26. if err != nil {
  27. fmt.Println(err)
  28. }
  29. defer res.Body.Close()
  30. body, err := ioutil.ReadAll(res.Body)
  31. if err != nil {
  32. fmt.Println(err)
  33. }
  34. var p Payload
  35. err = json.Unmarshal(body, &p)
  36. if err != nil {
  37. panic(err)
  38. }
  39. fmt.Println(p.Stuff.AccountID, "\n", p.Stuff.Actions, "\n",
  40. p.Stuff.AgentID, "\n", p.Stuff.AllocationState, "\n", p.Stuff.Compute,
  41. "\n", p.Stuff.Created, "\n", p.Stuff.Id, "\n", p.Stuff.Links)
  42. }

输出结果为:

  1. map[]
  2. map[]

这是服务器返回的JSON输出:

  1. {
  2. "type": "collection",
  3. "resourceType": "container",
  4. "links": {
  5. "self": ".../v1/containers"
  6. },
  7. "createTypes": {},
  8. "actions": {},
  9. "data": [
  10. {
  11. "id": "1i2",
  12. "type": "container",
  13. "links": { ... },
  14. "actions": { ... },
  15. "accountId": "1a1",
  16. "agentId": null,
  17. "allocationState": "active",
  18. "compute": null,
  19. "created": "2014-11-13T23:47:08Z",
  20. "createdTS": 1415922428119,
  21. "data": { ... },
  22. "description": null,
  23. "domain": null,
  24. "firstRunning": "2014-11-13T23:49:16Z",
  25. "firstRunningTS": 1415922556030,
  26. "hostname": null,
  27. "imageId": "1i1",
  28. "imageUuid": "docker:dockerfile/ghost:latest",
  29. "instanceTriggeredStop": "stop",
  30. "kind": "container",
  31. "memoryMb": 256,
  32. "name": "dockercontainer",
  33. "primaryAssociatedIpAddress": null,
  34. "primaryIpAddress": "0.0.0.0.",
  35. "removeTime": null,
  36. "removed": null,
  37. "requestedHostId": "1h1",
  38. "startOnCreate": true,
  39. "state": "running",
  40. "token": "xyz",
  41. "transitioning": "no",
  42. "transitioningMessage": null,
  43. "transitioningProgress": null,
  44. "userdata": null,
  45. "uuid": "29614f31-4322-4af4-9a55-d9c9395f5cb7",
  46. "validHostIds": null,
  47. "zoneId": "1z1",
  48. "environment": {},
  49. "command": null,
  50. "commandArgs": [],
  51. "directory": null,
  52. "user": null,
  53. "publishAllPorts": false,
  54. "privileged": false,
  55. "dockerVolumes": null,
  56. "ports": []
  57. },
  58. { ... }
  59. ],
  60. "sortLinks": { ... },
  61. "pagination": { ... },
  62. "sort": null,
  63. "filters": { ... },
  64. "createDefaults": {}
  65. }

希望对你有帮助!

英文:

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 -
{

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. )
  8. type Payload struct {
  9. Stuff Data
  10. }
  11. type Data struct {
  12. Id string
  13. Links Links_container
  14. Actions Actions_container
  15. AccountID string
  16. AgentID string
  17. AllocationState string
  18. Compute string
  19. Created string
  20. }
  21. type Links_container map[string]string
  22. type Actions_container map[string]string
  23. func main() {
  24. url := "http://localhost:8080/v1/containers"
  25. res, err := http.Get(url)
  26. if err != nil {
  27. fmt.Println(err)
  28. }
  29. defer res.Body.Close()
  30. body, err := ioutil.ReadAll(res.Body)
  31. if err != nil {
  32. fmt.Println(err)
  33. }
  34. var p Payload
  35. err = json.Unmarshal(body, &p)
  36. if err != nil {
  37. panic(err)
  38. }
  39. fmt.Println(p.Stuff.AccountID, "\n", p.Stuff.Actions, "\n",
  40. p.Stuff.AgentID, "\n", p.Stuff.AllocationState, "\n", p.Stuff.Compute,
  41. "\n", p.Stuff.Created, "\n", p.Stuff.Id, "\n", p.Stuff.Links)
  42. }

}

Output-

map[]

map[]

This is the JSON output from the server -

{

  1. "type": "collection",
  2. "resourceType": "container",
  3. "links": {
  4. "self": "…/v1/containers",
  5. },
  6. "createTypes": { },
  7. "actions": { },
  8. "data": [ 2 items
  9. {
  10. "id": "1i2",
  11. "type": "container",
  12. "links": { },
  13. "actions": { },
  14. "accountId": "1a1",
  15. "agentId": null,
  16. "allocationState": "active",
  17. "compute": null,
  18. "created": "2014-11-13T23:47:08Z",
  19. "createdTS": 1415922428119,
  20. "data": { },
  21. "description": null,
  22. "domain": null,
  23. "firstRunning": "2014-11-13T23:49:16Z",
  24. "firstRunningTS": 1415922556030,
  25. "hostname": null,
  26. "imageId": "1i1",
  27. "imageUuid": "docker:dockerfile/ghost:latest",
  28. "instanceTriggeredStop": "stop",
  29. "kind": "container",
  30. "memoryMb": 256,
  31. "name": "dockercontainer",
  32. "primaryAssociatedIpAddress": null,
  33. "primaryIpAddress": "0.0.0.0.",
  34. "removeTime": null,
  35. "removed": null,
  36. "requestedHostId": "1h1",
  37. "startOnCreate": true,
  38. "state": "running",
  39. "token": "xyz",
  40. "transitioning": "no",
  41. "transitioningMessage": null,
  42. "transitioningProgress": null,
  43. "userdata": null,
  44. "uuid": "29614f31-4322-4af4-9a55-d9c9395f5cb7",
  45. "validHostIds": null,
  46. "zoneId": "1z1",
  47. "environment": { },
  48. "command": null,
  49. "commandArgs": [ ],
  50. "directory": null,
  51. "user": null,
  52. "publishAllPorts": false,
  53. "privileged": false,
  54. "dockerVolumes": null,
  55. "ports": [ ],
  56. },
  57. { },
  58. ],
  59. "sortLinks": { },
  60. "pagination": { },
  61. "sort": null,
  62. "filters": { },
  63. "createDefaults": { },

}

答案1

得分: 2

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

你粘贴的JSON不是有效的(可以使用linter进行检查)。一旦确定输入的是有效的JSON,需要修改Go代码如下:

  • 字段需要使用选项进行“装饰”,告诉JSON解析器字段的名称是什么。
  • Payload 结构体根据你提供的JSON描述包含一个 Data 切片。

修改后的代码如下:

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. )
  8. type Payload struct {
  9. Stuff []Data `json:"data"`
  10. }
  11. type Data struct {
  12. Id string `json:"id"`
  13. Links Links_container `json:"links"`
  14. Actions Actions_container `json:"actions"`
  15. AccountID string `json:"accountId"`
  16. AgentID string `json:"agentId"`
  17. AllocationState string `json:"allocationState"`
  18. Compute string `json:"compute"`
  19. Created string `json:"created"`
  20. }
  21. type Links_container map[string]string
  22. type Actions_container map[string]string
  23. func main() {
  24. url := "http://localhost:8080/v1/containers"
  25. res, err := http.Get(url)
  26. if err != nil {
  27. fmt.Println(err)
  28. }
  29. defer res.Body.Close()
  30. body, err := ioutil.ReadAll(res.Body)
  31. if err != nil {
  32. fmt.Println(err)
  33. }
  34. var p Payload
  35. err = json.Unmarshal(body, &p)
  36. if err != nil {
  37. panic(err)
  38. }
  39. for _, stuff := range p.Stuff {
  40. fmt.Println(stuff.AccountID, "\n", stuff.Actions, "\n",
  41. stuff.AgentID, "\n", stuff.AllocationState, "\n", stuff.Compute,
  42. "\n", stuff.Created, "\n", stuff.Id, "\n", stuff.Links)
  43. }
  44. }

你可以在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:

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. )
  8. type Payload struct {
  9. Stuff []Data `json:"data"`
  10. }
  11. type Data struct {
  12. Id string `json:"id"`
  13. Links Links_container `json:"links"`
  14. Actions Actions_container `json:"actions"`
  15. AccountID string `json:"accountId"`
  16. AgentID string `json:"agentId"`
  17. AllocationState string `json:"allocationState"`
  18. Compute string `json:"compute"`
  19. Created string `json:"created"`
  20. }
  21. type Links_container map[string]string
  22. type Actions_container map[string]string
  23. func main() {
  24. url := "http://localhost:8080/v1/containers"
  25. res, err := http.Get(url)
  26. if err != nil {
  27. fmt.Println(err)
  28. }
  29. defer res.Body.Close()
  30. body, err := ioutil.ReadAll(res.Body)
  31. if err != nil {
  32. fmt.Println(err)
  33. }
  34. var p Payload
  35. err = json.Unmarshal(body, &p)
  36. if err != nil {
  37. panic(err)
  38. }
  39. for _, stuff := range p.Stuff {
  40. fmt.Println(stuff.AccountID, "\n", stuff.Actions, "\n",
  41. stuff.AgentID, "\n", stuff.AllocationState, "\n", stuff.Compute,
  42. "\n", stuff.Created, "\n", stuff.Id, "\n", stuff.Links)
  43. }
  44. }

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:

确定