Last active
September 29, 2015 20:38
-
-
Save cmelbye/bbd344907ab34aa435c6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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