How parse a http response?

hello how i have to parse an hhtttp response from a api?
resp, err := http.Get(“”)
if err != nil {
// handle error

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 (

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("")

	if err != nil {

	defer response.Body.Close()

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

	if err != nil {

	// 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 {

	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.


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.