mirror of
https://github.com/arnaucube/hermez-node.git
synced 2026-02-07 03:16:45 +01:00
In http servers, first listen, then serve
- In test, doing the `net.Listen` outside of the goroutine guarantees that we
are listening, so we avoid a possible datarace consisting of doing an http
request before listening.
- In packages that run an http server: doing the listen first allows
- Checking for errors when opening the address for listening before
starting the goroutine, so that if there's an error on listen we can
terminate grafecully
- Logging that we are listening when we are really listening, and not
before.
This commit is contained in:
11
node/node.go
11
node/node.go
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -444,16 +445,20 @@ func NewNodeAPI(
|
||||
// cancelation.
|
||||
func (a *NodeAPI) Run(ctx context.Context) error {
|
||||
server := &http.Server{
|
||||
Addr: a.addr,
|
||||
Handler: a.engine,
|
||||
// TODO: Figure out best parameters for production
|
||||
ReadTimeout: 30 * time.Second, //nolint:gomnd
|
||||
WriteTimeout: 30 * time.Second, //nolint:gomnd
|
||||
MaxHeaderBytes: 1 << 20, //nolint:gomnd
|
||||
}
|
||||
listener, err := net.Listen("tcp", a.addr)
|
||||
if err != nil {
|
||||
return tracerr.Wrap(err)
|
||||
}
|
||||
log.Infof("NodeAPI is ready at %v", a.addr)
|
||||
go func() {
|
||||
log.Infof("NodeAPI is ready at %v", a.addr)
|
||||
if err := server.ListenAndServe(); err != nil && tracerr.Unwrap(err) != http.ErrServerClosed {
|
||||
if err := server.Serve(listener); err != nil &&
|
||||
tracerr.Unwrap(err) != http.ErrServerClosed {
|
||||
log.Fatalf("Listen: %s\n", err)
|
||||
}
|
||||
}()
|
||||
|
||||
Reference in New Issue
Block a user