I am new to golang. I was writing a program to parse the json response of the API: https://httpbin.org/get. I have used the following code to parse the response:
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
)
type Headers struct {
Close string `json:"Connection"`
Accept string `json:"Accept"`
}
type apiResponse struct {
Header Headers `json:"headers"`
URL string `json:"url"`
}
func main() {
apiRoot := "https://httpbin.org/get"
req, err := http.NewRequest("GET", apiRoot, nil)
if err != nil {
fmt.Println("Couldn't prepare request")
os.Exit(1)
}
response, err := http.DefaultClient.Do(req)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer response.Body.Close()
var responseStruct apiResponse
err = json.NewDecoder(response.Body).Decode(&responseStruct)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Printf("%v
", responseStruct)
}
When I run this code the output is:
$ go run parse.go
{{close } https://httpbin.org/get}
From the output, as we can see the "Accept" key in json response is not decoded. Why is it so? How can I parse that string from response body?
Your code is doing well but here I think your Accept
key does not return from API that's why it's not showing the Accept
value. To check the key
, value
pair of your struct, use the below print
method.
fmt.Printf("%+v
", responseStruct)
To overcome from this situation you need to send Accept
with request into header
before request the API like:
req.Header.Set("Accept", "value")
response, err := hc.Do(req)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
Then you will get the Accept
value in decoded
struct as :
{Header:{Accept:value Close:close} URL:https://httpbin.org/get}
apiResponse is unexported - you need to change it to something like APIResponse. You may find that pasting the JSON you want to decode into https://mholt.github.io/json-to-go/ will make all the code you need!
type AutoGenerated struct {
Args struct {
} `json:"args"`
Headers struct {
Accept string `json:"Accept"`
AcceptEncoding string `json:"Accept-Encoding"`
AcceptLanguage string `json:"Accept-Language"`
Connection string `json:"Connection"`
Dnt string `json:"Dnt"`
Host string `json:"Host"`
UpgradeInsecureRequests string `json:"Upgrade-Insecure-Requests"`
UserAgent string `json:"User-Agent"`
} `json:"headers"`
Origin string `json:"origin"`
URL string `json:"url"`
}