hey how i’ve to parse an hhtttp response from a api?
resp, err := http.Get(“https://api.kraken.com/0/public/Time”)
if err != nil {
// deal with error
}
fmt.Println(resp.Physique)
???
i dont know the way i may have entry to the sector
Once you obtain a json because the response, you’ll have to make use of the encoding/json
bundle to do the parsing.
For instance, say I made a name and the endpoint responded with:
{
"title": "Jhon",
"age": 87
}
Right here’s the way you’d parse that:
bundle foremost
import (
"encoding/json"
"fmt"
"io/ioutil"
"internet/http"
)
sort Individual struct {
Title string `json:"title"` // Uppercased first letter
Age int `json:"age"` // Uppercased first letter
}
func foremost() {
var p Individual
response, err := http.Get("http://someplace.com/api/folks/999")
if err != nil {
panic(err)
}
defer response.Physique.Shut()
// learn the payload, on this case, Jhon's information
physique, err := ioutil.ReadAll(response.Physique)
if err != nil {
panic(err)
}
// that is the place the magic occurs, I move a pointer of sort Individual and Go'll do the remaining
err = json.Unmarshal(physique, &p)
if err != nil {
panic(err)
}
fmt.Println(p.Title) // Jhon
fmt.Println(p.Age) // 87
}
Now all it’s important to do is, as a substitute of utilizing the Individual
sort, use one that matches what’s your endpoint is sending you.
1 Like
thanks a lot i’ve performed in the identical method
Only a query what’s the panic( err) ??
The panic and recuperate features behave equally to exceptions and check out/catch in another languages in {that a} panic causes this system stack to start unwinding and recuperate can cease it. Deferred features are nonetheless executed because the stack unwinds. If recuperate is known as inside such a deferred operate, the stack stops unwinding and recuperate returns the worth (as an interface{}) that was handed to panic. The runtime can even panic in extraordinary circumstances, similar to indexing an array or slice out-of-bounds. If a panic causes the stack to unwind exterior of any executing goroutine (e.g. foremost or the top-level operate given to go fail to recuperate from it), this system exits with a stack hint of all executing goroutines. A panic can’t be recovered by a unique goroutine.
Additionally, there are different good explanations concerning the topic on the market.
ought to keep away from utilizing ioutil.ReadAll(response Physique)
As a substitute ought to do that
resp, err := http.Get("https://instance.com/api/1")
if err != nil {
return errorMessage
}
sort Response struct {
Sort string `json:"sort"`
}
if err := json.NewDecoder(resp.Physique).Decode(&Response); err != nil {
return errorMessage
}
Two issues which could be performed extra effectively: Use StringBuilder as a substitute of StringBuffer because it’s the sooner and youthful brother.
And what’s the second factor?