9.4. Joke API
Task
Try and solve the following. Every task has links to relevant documentation.
API Client
- Begin with the following main.go which requests a joke from https://official-joke-api.appspot.com/random_joke and decodes it into a Go struct.
- Refactor the HTTP request into another function
that returns
joke, error - Update the code to also decode and print the punchline
- Delay the punchline by a few seconds
- Make the delay configurable with a
--delay 10flag
Some tips regarding flags
We recommend using flag.IntVar , instead of flag.Int . Both variants work, but with flag.IntVar you end up with a normal variable, instead of a pointer . You may also try using flag.DurationVar .
To learn more about the *int type, see 2.4. Pointers.
Do not forget to run flag.Parse() after defining the flags.
Error: mismatched types int and time.Duration
When solving the last task, you might receive the error: mismatched types int and time.Duration. This is because you cannot multiply different types. You must first convert the value to the same type.
i := 42
f := float64(i)
u := uint(f)
d := time.Duration(u)
For more information why 5 * time.Second works see:
https://stackoverflow.com/a/49498375
API Server
- Write another program that reads a json file and picks a random joke. You will need to use slices
- Implement a HTTP Server that serves the picked joke
- Update your program from part one so that you can configure the URL (maybe as another flag) and query your own API
Add jokes
- Extend your HTTP Server that you can send a joke to it which gets persisted (POST request)
- Extend your program from part one that it supports adding new jokes. For this ask the user to enter a joke on the command line (standard input) and send it to your own API.
Prompt for input on the command line (standard input)
With the bufio package we can read from the standard input (os.Stdin ) until a certain character occurs:
line, err := bufio.NewReader(os.Stdin).ReadString('\n')
The strings package contains various functions to work with strings. For example strings.TrimSpace to remove whithspace characters (spaces, newlines, etc.) from strings.
line = strings.TrimSpace(line)