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)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 微信小程序请求失败,网页能正常带锁访问
  • ¥15 对语音信号进行变调时,间接改变时序从而实现语音变速,进而将变调与变速同时实现、参数合成法换为波形合成法
  • ¥30 德飞莱51单片机实现C4炸弹
  • ¥50 CrossLink-LIF-MD6000 型 FPGA 的 CMOS 转 MIPI D-PHY IP 核功能使用异常
  • ¥15 proteus控制16x16LED点阵显示屏的设计
  • ¥30 求会做山景bp1048b2程序的。做直播声卡用
  • ¥15 求数学建模论文问题指导
  • ¥15 51单片机与数码管实现电子琴
  • ¥15 h3.6m 人类行为预测论文复现
  • ¥50 wordpress项目注册报失败刷新后其实是成功状态,请求排查原因