Skip to content

Instantly share code, notes, and snippets.

@chico
Created February 24, 2022 09:04
Show Gist options
  • Save chico/0badd2447590b7e0e4ca7a51e2bc58ea to your computer and use it in GitHub Desktop.
Save chico/0badd2447590b7e0e4ca7a51e2bc58ea to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"time"
)
type jokejson struct {
Joke string `json:"joke"`
}
func main() {
url := "https://sv443.net/jokeapi/v2/joke/Programming?type=single"
c := http.Client{
Timeout: time.Second * 30,
}
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
log.Fatal(err)
}
res, getErr := c.Do(req)
if getErr != nil {
log.Fatal(getErr)
}
if res.Body != nil {
defer res.Body.Close()
}
body, readErr := ioutil.ReadAll(res.Body)
if readErr != nil {
log.Fatal(readErr)
}
j := jokejson{}
jsonErr := json.Unmarshal(body, &j)
if jsonErr != nil {
log.Fatal(jsonErr)
}
fmt.Printf(j.Joke)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment