Skip to content

Commit

Permalink
fix: use of log.Fatal in main
Browse files Browse the repository at this point in the history
Remove use of log fatal which prevents defers and correct order of Write
and WriteHeader.
  • Loading branch information
stevenh committed Aug 19, 2024
1 parent ca76ee1 commit 00c2f7d
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 8 deletions.
11 changes: 5 additions & 6 deletions testdata/echoserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,8 @@ import (

func envHandler() http.HandlerFunc {
return func(rw http.ResponseWriter, req *http.Request) {
_, _ = rw.Write([]byte(os.Getenv("FOO")))

rw.WriteHeader(http.StatusAccepted)
rw.Write([]byte(os.Getenv("FOO"))) //nolint:errcheck // Nothing we can usefully do with the error here.
}
}

Expand All @@ -21,9 +20,7 @@ func echoHandler(destination *os.File) http.HandlerFunc {
echo := req.URL.Query()["echo"][0]

l := log.New(destination, "echo ", 0)

l.Println(echo)
_ = destination.Sync()

rw.WriteHeader(http.StatusAccepted)
}
Expand All @@ -39,10 +36,12 @@ func main() {

ln, err := net.Listen("tcp", ":8080")
if err != nil {
panic(err)
log.Fatal(err)
}

fmt.Println("ready")

_ = http.Serve(ln, mux)
if err := http.Serve(ln, mux); err != nil {
log.Fatal(err)
}
}
15 changes: 13 additions & 2 deletions wait/testdata/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"context"
"encoding/base64"
"errors"
"fmt"
"io"
"log"
"net/http"
Expand All @@ -15,7 +16,7 @@ import (
"time"
)

func main() {
func run() error {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(http.StatusOK)
Expand Down Expand Up @@ -93,5 +94,15 @@ func main() {
log.Println("stopping...")
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
_ = server.Shutdown(ctx)
if err := server.Shutdown(ctx); err != nil {
return fmt.Errorf("shutdown: %w", err)
}

return nil
}

func main() {
if err := run(); err != nil {
log.Fatal(err)
}
}

0 comments on commit 00c2f7d

Please sign in to comment.