Golang发送POST请求并返回JSON响应

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

Golang post return json response

问题

我正在尝试使用Golang向我的Magento网服务器发出请求。

我成功地进行了POST请求,但是,当我使用cmd中的CURL时,我没有得到相同的响应。
我按照这篇帖子(https://stackoverflow.com/questions/17156371/how-to-get-json-response-in-golang)的方法,但没有得到任何响应。

所以我尝试了以下代码:

package main

import (
	"fmt"
	"net/http"
	"os"
)

var protocol = "http://"
var baseURL = protocol + "myserver.dev"

func main() {

	fmt.Print("Start API Test on: " + baseURL + "\n")
	r := getCart()
	fmt.Print(r)
}

func getCart() *http.Response {
	resp, err := http.Post(os.ExpandEnv(baseURL+"/index.php/rest/V1/guest-carts/"), "", nil)
	if err != nil {
		fmt.Print(err)
	}

	return resp
}

这只返回了HTTP响应,如下所示:

{200 OK 200 HTTP/1.1 1 1 map[Date:[Thu, 04 May 2017 05:30:20 GMT] Content-Type:[application/json; charset=utf-8] Set-Cookie:[PHPSESSID=elklkflekrlfekrlklkl; expires=Thu, 04-May-2017 ...

当我使用curl -g -X POST "my.dev/index.php/rest/V1/guest-carts/"时,我会得到一些我需要继续进行的ID。
如何在Golang中获取这个CURL的结果呢?

英文:

I'm trying to make a request to my (magento)webserver using golang.

I managed to make a POST request, but however, I'm not getting the same response I'm getting when using CURL from the cmd.
I followed this post (https://stackoverflow.com/questions/17156371/how-to-get-json-response-in-golang) which does not give me any response.

So I tried this

package main

import (
	"fmt"
	"net/http"
	"os"
)

var protocol = "http://"
var baseURL = protocol + "myserver.dev"

func main() {

	fmt.Print("Start API Test on: " + baseURL + "\n")
	r := getCart()
	fmt.Print(r)
}

func getCart() *http.Response {
	resp, err := http.Post(os.ExpandEnv(baseURL+"/index.php/rest/V1/guest-carts/"), "", nil)
	if err != nil {
		fmt.Print(err)
	}

	return resp
}

This just return the http reponse like

{200 OK 200 HTTP/1.1 1 1 map[Date:[Thu, 04 May 2017 05:30:20 GMT] Content-Type:[application/json; charset=utf-8] Set-Cookie:[PHPSESSID=elklkflekrlfekrlklkl; expires=Thu, 04-May-2017 ...

When using curl -g -X POST "my.dev/index.php/rest/V1/guest-carts/" I retrieve some kind of ID which I need to proceed.
How can I get the this curl result in golang?

答案1

得分: 4

你需要读取resp.Body(别忘了关闭它!),例如:

func main() {
    fmt.Print("Start API Test on: " + baseURL + "\n")
    r := getCart()
    defer r.Body.Close()
    if _, err := io.Copy(os.Stdout, r.Body); err != nil {
        fmt.Print(err)
    }
}
英文:

You need to read the resp.Body (and don't forget to close it!), ie

func main() {
    fmt.Print("Start API Test on: " + baseURL + "\n")
    r := getCart()
    defer r.Body.Close();
    if _, err := io.Copy(os.Stdout, r.Body); err != nil {
       fmt.Print(err)
    }
}

huangapple
  • 本文由 发表于 2017年5月4日 13:36:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/43774619.html
匿名

发表评论

匿名网友

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

确定