doupo1908 2017-05-04 05:36
浏览 187
已采纳

Golang发布返回JSON响应

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 (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 + "
")
    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条回答 默认 最新

  • douduidui1046 2017-05-04 05:46
    关注

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

    func main() {
        fmt.Print("Start API Test on: " + baseURL + "
    ")
        r := getCart()
        defer r.Body.Close();
        if _, err := io.Copy(os.Stdout, r.Body); err != nil {
           fmt.Print(err)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 docker模式webrtc-streamer 无法播放公网rtsp
  • ¥15 学不会递归,理解不了汉诺塔参数变化
  • ¥15 基于图神经网络的COVID-19药物筛选研究
  • ¥30 软件自定义无线电该怎样使用
  • ¥15 R语言mediation包做中介分析,直接效应和间接效应都很小,为什么?
  • ¥15 Jenkins+k8s部署slave节点offline
  • ¥15 如何实现从tello无人机上获取实时传输的视频流,然后将获取的视频通过yolov5进行检测
  • ¥15 WPF使用Canvas绘制矢量图问题
  • ¥15 用三极管设计一个单管共射放大电路
  • ¥15 孟德尔随机化r语言运行问题