How parse a http response?

hello how i have to parse an hhtttp response from a api?
resp, err := http.Get(“https://api.kraken.com/0/public/Time”)
if err != nil {
// handle error
}
fmt.Println(resp.Body)

???
i dont know how i could have access to the field

When you receive a json as the response, you’ll have to use the encoding/json package to do the parsing.

For example, say I made a call and the endpoint responded with:

{
   "name": "Jhon",
   "age": 87
}

Here’s how you’d parse that:

package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

type Person struct {
	Name string `json:"name"` // Uppercased first letter
	Age  int    `json:"age"`  // Uppercased first letter
}

func main() {
	var p Person

	response, err := http.Get("http://somewhere.com/api/people/999")

	if err != nil {
		panic(err)
	}

	defer response.Body.Close()

	// read the payload, in this case, Jhon's info
	body, err := ioutil.ReadAll(response.Body)

	if err != nil {
		panic(err)
	}

	// this is where the magic happens, I pass a pointer of type Person and Go'll do the rest
	err = json.Unmarshal(body, &p)

	if err != nil {
		panic(err)
	}

	fmt.Println(p.Name) // Jhon
	fmt.Println(p.Age) // 87
}

Now all you have to do is, instead of using the Person type, use one that fits what’s your endpoint is sending you.

1 Like

thank you so much i have done in the same way
Just a question what is the panic( err) ??

The panic and recover functions behave similarly to exceptions and try/catch in some other languages in that a panic causes the program stack to begin unwinding and recover can stop it. Deferred functions are still executed as the stack unwinds. If recover is called inside such a deferred function, the stack stops unwinding and recover returns the value (as an interface{}) that was passed to panic. The runtime will also panic in extraordinary circumstances, such as indexing an array or slice out-of-bounds. If a panic causes the stack to unwind outside of any executing goroutine (e.g. main or the top-level function given to go fail to recover from it), the program exits with a stack trace of all executing goroutines. A panic cannot be recovered by a different goroutine.

Also, there are other good explanations about the subject out there.

should avoid using ioutil.ReadAll(response Body)

Instead should do this

resp, err := http.Get("https://example.com/api/1")
if err != nil {
  return errorMessage
}

type Response struct {
  Type string `json:"type"`
}

if err := json.NewDecoder(resp.Body).Decode(&Response); err != nil {
  return errorMessage
}