doupo1908
2017-05-04 05:36
浏览 119

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?

图片转代码服务由CSDN问答提供 功能建议

我正在尝试使用golang向我的(magento)网络服务器发出请求。 \ n

我设法发出了POST请求,但是,从cmd使用CURL时,我没有得到与我相同的响应。 我关注了这篇文章(如何在Golang中获取JSON响应),但没有任何响应。

所以我尝试了这个

 程序包main 
 
import(
“ fmt” 
“ net / http” 
“ os” 
)
  
var协议=“ http://” 
var baseURL =协议+“ myserver.dev” 
 
func main(){
 
 fmt.Print(“在以下位置启动API测试:” + baseURL +“ 
  “)
r:= getCart()
 fmt.Print(r)
} 
 
func getCart()* http.Response {
 resp,err:= http.Post(os.ExpandEnv(baseURL +” /  index.php / rest / V1 / guest-carts /“),”“,nil)
如果错误!= nil {
 fmt.Print(err)
} 
 
 return resp 
} 
    
 
 

这只会返回

  {200 OK 200 HTTP / 1.1 1 1 map [Date:[Thu,2017年5月4日05:30:20 GMT]内容类型:[application / json;  charset = utf-8] Set-Cookie:[PHPSESSID = elklkflekrlfekrlklkl;  expires =星期四,2017年5月4日... 
   
 
 

使用 curl -g -X POST“ my.dev/index.php/rest / V1 / guest-carts /“ 我检索了一些我需要继续进行的ID。 如何在golang中获取此curl结果?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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)
        }
    }
    
    点赞 打赏 评论

相关推荐 更多相似问题