xhallix
xhallix

Reputation: 3011

Golang post return json response

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 + "\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?

Upvotes: 1

Views: 1977

Answers (1)

ain
ain

Reputation: 22749

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)
    }
}

Upvotes: 4

Related Questions