Skip to content

Instantly share code, notes, and snippets.

@farhaanbukhsh
Last active April 20, 2018 07:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save farhaanbukhsh/c428cd6a66e05d964c34ee1cea88ce61 to your computer and use it in GitHub Desktop.
Save farhaanbukhsh/c428cd6a66e05d964c34ee1cea88ce61 to your computer and use it in GitHub Desktop.
The initial cut of chuck
// 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