Overview
Read a port number from a config value in Go with strconv.Atoi, returning an error for text or out-of-range numbers instead of silently using 0.
- a second return value for the error
- check err != nil right away
- never drop an error with _
Short Course
Go functions return an error as their last value, and you check err != nil
right away. Trap: n, _ := strconv.Atoi(s) throws the error away, and bad
input silently becomes 0.
n, err := strconv.Atoi("42") // 42, nil
n, err = strconv.Atoi("x") // 0, error
if err != nil {
return 0, err
}
Task
Write ParsePort(s string) (int, error): the port as a number, or 0 and an
error if s isn't a whole number from 0 to 65535 (0 means "any free port").
Example: ParsePort("8080") → 8080, nil.
Test Suites
Pending
Next
Output