10 The standard library

 

This chapter covers

  • Providing a correct time duration
  • Understanding potential memory leaks while using time.After
  • Avoiding common mistakes in JSON handling and SQL
  • Closing transient resources
  • Remembering the return statement in HTTP handlers
  • Why production-grade applications shouldn’t use default HTTP clients and servers

The Go standard library is a set of core packages that enhance and extend the language. For example, Go developers can write HTTP clients or servers, handle JSON data, or interact with SQL databases. All of these features are provided by the standard library. However, it can be easy to misuse the standard library, or we may have a limited understanding of its behavior, which can lead to bugs and writing applications that shouldn’t be considered production-grade. Let’s look at some of the most common mistakes while using the standard library.

10.1 #75: Providing a wrong time duration

The standard library provides common functions and methods that accept a time.Duration. However, because time.Duration is an alias for the int64 type, newcomers to the language can get confused and provide a wrong duration. For example, developers with a Java or JavaScript background are used to passing numeric types.

To illustrate this common error, let’s create a new time.Ticker that will deliver the ticks of a clock every second:

ticker := time.NewTicker(1000)
for {
    select {
    case <-ticker.C:
        // Do something
    }
}

10.2 #76: time.After and memory leaks

10.3 #77: Common JSON-handling mistakes

10.3.1 Unexpected behavior due to type embedding

10.3.2 JSON and the monotonic clock

10.3.3 Map of any

10.4 #78: Common SQL mistakes

10.4.1 Forgetting that sql.Open doesn’t necessarily establish connections to a database

10.4.2 Forgetting about connections pooling