Skip to content

Instantly share code, notes, and snippets.

@tonvanbart
Created January 17, 2022 15:08
Show Gist options
  • Save tonvanbart/f093cedf248ab69abc45e1214f0e0bf1 to your computer and use it in GitHub Desktop.
Save tonvanbart/f093cedf248ab69abc45e1214f0e0bf1 to your computer and use it in GitHub Desktop.
Small Go program to read number of people in space from a webservice
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
)
type Astronaut struct {
Craft string `json:"craft"`
Name string `json:"name"`
}
type AstronautResponse struct {
People []Astronaut `json:"people"`
Message string `json:"message"`
Number int64 `json:"number"`
}
func main() {
fmt.Println("how many people are in space right now?")
resp, err := http.Get("http://api.open-notify.org/astros.json")
if err != nil {
fmt.Println("error retrieving url", err)
}
status := resp.StatusCode
fmt.Println("Response status code=", status)
// fmt.Println("response is ", resp)
body, err := io.ReadAll(resp.Body)
resp.Body.Close()
fmt.Println("Response body=\n", string(body[:]), "\n")
fmt.Println("length of returned byte array:", len(body))
var response = new(AstronautResponse)
err2 := json.Unmarshal(body, &response)
if err2 != nil {
fmt.Println("Oops, error:", err2)
} else {
fmt.Println("Number:", response.Number)
fmt.Println("array length:", len(response.People))
fmt.Println("First array elt:", response.People[1].Name)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment