Skip to content

Commit

Permalink
Merge pull request #62 from jushutch/summarize-80
Browse files Browse the repository at this point in the history
Summarize mistake 80
  • Loading branch information
teivah authored Nov 28, 2023
2 parents 668d616 + e239cd1 commit 70ff3de
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -1823,6 +1823,48 @@ ticker = time.NewTicker(1000 * time.Nanosecond)

To avoid unexpected behaviors in HTTP handler implementations, make sure you don’t miss the `return` statement if you want a handler to stop after `http.Error`.

Consider the following HTTP handler that handles an error from `foo` using `http.Error`:

```go
func handler(w http.ResponseWriter, req *http.Request) {
err := foo(req)
if err != nil {
http.Error(w, "foo", http.StatusInternalServerError)
}

_, _ = w.Write([]byte("all good"))
w.WriteHeader(http.StatusCreated)
}
```

If we run this code and `err != nil`, the HTTP response would be:

```
foo
all good
```

The response contains both the error and success messages, and also the first HTTP status code, 500. There would also be a warning log indicating that we attempted to write the status code multiple times:

```
2023/10/10 16:45:33 http: superfluous response.WriteHeader call from main.handler (main.go:20)
```

The mistake in this code is that `http.Error` does not stop the handler's execution, which means the success message and status code get written in addition to the error. Beyond an incorrect response, failing to return after writing an error can lead to the unwanted execution of code and unexpected side-effects. The following code adds the `return` statement following the `http.Error` and exhibits the desired behavior when ran:

```go hl_lines="5"
func handler(w http.ResponseWriter, req *http.Request) {
err := foo(req)
if err != nil {
http.Error(w, "foo", http.StatusInternalServerError)
return
}

_, _ = w.Write([]byte("all good"))
w.WriteHeader(http.StatusCreated)
}
```

[Source code :simple-github:](https://github.com/teivah/100-go-mistakes/tree/master/src/10-standard-lib/80-http-return/main.go)

### Using the default HTTP client and server (#81)
Expand Down

0 comments on commit 70ff3de

Please sign in to comment.