英文:
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)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论