Skip to content

Instantly share code, notes, and snippets.

@cmelbye
Last active September 29, 2015 20:38
Show Gist options
  • Save cmelbye/bbd344907ab34aa435c6 to your computer and use it in GitHub Desktop.
Save cmelbye/bbd344907ab34aa435c6 to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"errors"
"log"
"net/http"
)
/*
This code won't work, because it's not hitting a real API,
but pretend that the API returns this JSON response:
GET /users/123
{
"id": 123,
"first_name": "John",
"last_name": "Doe"
}
*/
func getJSON(endpoint string, val interface{}) error {
resp, err := http.Get("https://myapi.com/" + endpoint)
if err != nil {
return err
}
// Close the response body when this function returns.
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return errors.New("api: non-200 response code")
}
dec := json.NewDecoder(resp.Body)
return dec.Decode(val)
}
type User struct {
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
ID int `json:"id"`
}
func main() {
var user User
if err := getJSON("users/123", &user); err != nil {
log.Fatal(err)
}
log.Printf("Hello, %s!", user.FirstName)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment