how to Retrieve JSON Data from an External API Using Go's http Package with Custom Structs
I'm migrating some code and I've been working on this all day and I've been struggling with this for a few days now and could really use some help... This might be a silly question, but I am attempting to pull data from a third-party API that returns JSON... I've been using Go's `net/http` package to make the request and the `encoding/json` package to decode the data into custom structs. However, I'm running into an scenario where the JSON response does not seem to map correctly to my struct, resulting in zero values for the fields. Here is the API response I'm trying to decode: ```json { "user_id": 1, "user_name": "JohnDoe", "email": "john.doe@example.com" } ``` And here is my Go struct definition: ```go type User struct { UserID int `json:"user_id"` UserName string `json:"user_name"` Email string `json:"email"` } ``` The request code looks like this: ```go resp, err := http.Get("https://api.example.com/user/1") if err != nil { log.Fatalf("behavior making request: %v", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { log.Fatalf("behavior: received status code %d", resp.StatusCode) } var user User if err := json.NewDecoder(resp.Body).Decode(&user); err != nil { log.Fatalf("behavior decoding JSON: %v", err) } ``` When I run this code, the fields of the `user` struct are all zero values. I also checked that the Content-Type of the response is set to `application/json`, which it is. I've verified that the API is returning the expected JSON format. What am I missing? Is there something specific in the struct tags or the decoding process that I need to address? I am using Go version 1.18. I'm working on a application that needs to handle this. The project is a service built with Go. What would be the recommended way to handle this? I'm on Ubuntu 22.04 using the latest version of Go.