refactor: use mock transport in watch order tests and harden server timeouts
This commit is contained in:
@@ -5,6 +5,7 @@ import (
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/render"
|
||||
@@ -34,28 +35,39 @@ func RunServer(lifecycle fx.Lifecycle, r *gin.Engine) {
|
||||
port = "3000"
|
||||
}
|
||||
|
||||
srv := &http.Server{
|
||||
Addr: ":" + port,
|
||||
Handler: r,
|
||||
}
|
||||
srv := newHTTPServer(":"+port, r)
|
||||
|
||||
lifecycle.Append(fx.Hook{
|
||||
OnStart: func(context.Context) error {
|
||||
log.Printf("Starting server on http://localhost:%s", port)
|
||||
go func() {
|
||||
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
log.Fatalf("listen: %s\n", err)
|
||||
// Avoid exiting the process from a goroutine; let the process supervisor handle restarts.
|
||||
log.Printf("server listen error: %s", err)
|
||||
}
|
||||
}()
|
||||
return nil
|
||||
},
|
||||
OnStop: func(ctx context.Context) error {
|
||||
log.Println("Shutting down server...")
|
||||
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||
defer cancel()
|
||||
return srv.Shutdown(ctx)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func newHTTPServer(addr string, handler http.Handler) *http.Server {
|
||||
return &http.Server{
|
||||
Addr: addr,
|
||||
Handler: handler,
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
ReadTimeout: 30 * time.Second,
|
||||
WriteTimeout: 30 * time.Second,
|
||||
IdleTimeout: 2 * time.Minute,
|
||||
}
|
||||
}
|
||||
|
||||
// RouteRegister is an interface that modules can implement to register their routes.
|
||||
type RouteRegister interface {
|
||||
Register(r *gin.Engine)
|
||||
|
||||
28
internal/server/server_test.go
Normal file
28
internal/server/server_test.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestNewHTTPServer_TimeoutsAndAddr(t *testing.T) {
|
||||
srv := newHTTPServer(":1234", http.NewServeMux())
|
||||
|
||||
if srv.Addr != ":1234" {
|
||||
t.Fatalf("Addr: got %q want %q", srv.Addr, ":1234")
|
||||
}
|
||||
if srv.ReadHeaderTimeout != 5*time.Second {
|
||||
t.Fatalf("ReadHeaderTimeout: got %s want %s", srv.ReadHeaderTimeout, 5*time.Second)
|
||||
}
|
||||
if srv.ReadTimeout != 30*time.Second {
|
||||
t.Fatalf("ReadTimeout: got %s want %s", srv.ReadTimeout, 30*time.Second)
|
||||
}
|
||||
if srv.WriteTimeout != 30*time.Second {
|
||||
t.Fatalf("WriteTimeout: got %s want %s", srv.WriteTimeout, 30*time.Second)
|
||||
}
|
||||
if srv.IdleTimeout != 2*time.Minute {
|
||||
t.Fatalf("IdleTimeout: got %s want %s", srv.IdleTimeout, 2*time.Minute)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user