Last active
April 20, 2018 07:00
-
-
Save farhaanbukhsh/c428cd6a66e05d964c34ee1cea88ce61 to your computer and use it in GitHub Desktop.
The initial cut of chuck
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
// Chucknorris is the struct used to unmarshal the JSON response from the URL | |
type Chucknorris struct { | |
Category []string `json:"category"` | |
IconURL string `json:"icon_url"` | |
ID string `json:"id"` | |
URL string `json:"url"` | |
Value string `json:"value"` | |
} | |
/* getJokes takes the API url as the parameter and fetch jokes from it, | |
* here we have assumed it to be of ChuckNorris type | |
*/ | |
//TODO: Remove the dependency on the hardcoded struct | |
func getJokes(URL string) (string, error) { | |
req, err := http.NewRequest("GET", URL, nil) | |
if err != nil { | |
return "", fmt.Errorf("No request formed %v", err) | |
} | |
client := &http.Client{} | |
resp, err := client.Do(req) | |
if err != nil { | |
return "", fmt.Errorf("No response: %v", err) | |
} | |
defer resp.Body.Close() | |
respData, err := ioutil.ReadAll(resp.Body) | |
if err != nil { | |
return "", fmt.Errorf("Read error") | |
} | |
var joke Chucknorris | |
if err = json.Unmarshal(respData, &joke); err != nil { | |
return "", fmt.Errorf("Error in unmarsheling, %v", err) | |
} | |
return joke.Value, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment