Time, io, and slog
Durations are parsed by time.ParseDuration. Logs in a service are structured, through log/slog.
time.Duration is a number of nanoseconds wrapped in a type. time.ParseDuration("250ms") understands strings such as ns, ms, s, m, h. For hours and minutes that is convenient in config. For calendar dates take time.Time and time.Parse with a layout, not a duration.
The monotonic clock inside time.Time is good for measuring an interval. time.Since(start) does not jump when the system clock is changed. For a request deadline you still take a context, not your own Sleep.
io.Reader and io.Writer are the joint of almost all input and output. io.Copy moves bytes until the source ends. The copy error is not thrown away. bytes.Buffer gathers bytes in memory and is good in tests instead of a socket.
The log in a service is log/slog. The message is short. The details go in fields:
slog.Info("запрос", "method", r.Method, "path", r.URL.Path, "status", code)
A journal like that can be filtered. fmt.Sprintf into one string with no fields fits a script, not a service. The Error level is for failures, Info for expected events such as startup and a request. Do not write Error on every 404: that is an ordinary response, not a broken process.
slog can take a context (InfoContext), so the record picks up fields that middleware put into the logger. A global slog.Info in a handler is acceptable at the start. When different sinks appear, the logger is passed explicitly, like the database and the clock.
Practice
Milliseconds from a string
Write
Millis(d string) int. Parse a duration in the format oftime.ParseDurationand return the whole number of milliseconds. For a string that cannot be parsed, return-1.A log level
A client requested an unknown path, and the handler answers 404. Which level is appropriate if the service is healthy?
- Error. Any 4xx code is a breakdown
- Info or below. This is an ordinary response
- Panic
- No log exists in the standard library
io.Copy
What should you do with the error that
io.Copyreturned?- Ignore it. Copy always reads to the end
- Return it or handle it at the boundary
- Turn it into a panic
- Always compare its text with EOF by hand, even if there is no error