In Go, you can read JSON from an HTTP response body using the encoding/json package. Here's how to do it:
Basic Example
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
)
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
}
func main() {
resp, err := http.Get("https://api.example.com/user/1")
if err != nil {
panic(err)
}
defer resp.Body.Close()
// Read the body
body, err := io.ReadAll(resp.Body)
if err != nil {
panic(err)
}
// Parse JSON
var user User
err = json.Unmarshal(body, &user)
if err != nil {
panic(err)
}
fmt.Printf("User: %+v\n", user)
}
Direct Decoding (More Efficient)
Instead of reading the entire body into memory first, you can decode directly from the response body:
func main() {
resp, err := http.Get("https://api.example.com/user/1")
if err != nil {
panic(err)
}
defer resp.Body.Close()
// Decode directly from response body
var user User
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(&user)
if err != nil {
panic(err)
}
fmt.Printf("User: %+v\n", user)
}
Handling Arrays/Slices
For JSON arrays:
var users []User
err = json.NewDecoder(resp.Body).Decode(&users)
Error Handling Best Practices
func fetchUser(url string) (*User, error) {
resp, err := http.Get(url)
if err != nil {
return nil, fmt.Errorf("failed to make request: %w", err)
}
defer resp.Body.Close()
// Check status code
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("unexpected status: %s", resp.Status)
}
var user User
if err := json.NewDecoder(resp.Body).Decode(&user); err != nil {
return nil, fmt.Errorf("failed to decode JSON: %w", err)
}
return &user, nil
}
Working with Dynamic JSON
If you don't know the structure beforehand:
var result map[string]interface{}
err = json.NewDecoder(resp.Body).Decode(&result)
// Or for arrays
var results []map[string]interface{}
err = json.NewDecoder(resp.Body).Decode(&results)
The json.NewDecoder approach is generally preferred because it's more memory efficient for large responses and allows you to set decoder options if needed.