Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(net/ghttp): occasional ci failed by unit testing cases using gctp.GetFreePort #3982

Merged
merged 10 commits into from
Dec 10, 2024
40 changes: 20 additions & 20 deletions net/ghttp/ghttp.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"sync"
"time"

"github.com/gogf/gf/v2/net/ghttp/internal/gracefulserver"
"github.com/gorilla/websocket"

"github.com/gogf/gf/v2/container/gmap"
Expand All @@ -34,7 +35,7 @@ type (
instance string // Instance name of current HTTP server.
config ServerConfig // Server configuration.
plugins []Plugin // Plugin array to extend server functionality.
servers []*gracefulServer // Underlying http.Server array.
servers []*gracefulserver.Server // Underlying http.Server array.
serverCount *gtype.Int // Underlying http.Server number for internal usage.
closeChan chan struct{} // Used for underlying server closing event notification.
serveTree map[string]interface{} // The route maps tree.
Expand Down Expand Up @@ -127,7 +128,7 @@ type (

const (
// FreePortAddress marks the server listens using random free port.
FreePortAddress = ":0"
FreePortAddress = gracefulserver.FreePortAddress
)

const (
Expand All @@ -136,33 +137,32 @@ const (
HookAfterServe HookName = "HOOK_AFTER_SERVE" // Hook handler after route handler/file serving.
HookBeforeOutput HookName = "HOOK_BEFORE_OUTPUT" // Hook handler before response output.
HookAfterOutput HookName = "HOOK_AFTER_OUTPUT" // Hook handler after response output.
ServerStatusStopped ServerStatus = 0
ServerStatusRunning ServerStatus = 1
DefaultServerName = "default"
DefaultDomainName = "default"
HandlerTypeHandler HandlerType = "handler"
HandlerTypeObject HandlerType = "object"
HandlerTypeMiddleware HandlerType = "middleware"
HandlerTypeHook HandlerType = "hook"
ServerStatusStopped ServerStatus = gracefulserver.ServerStatusStopped
ServerStatusRunning ServerStatus = gracefulserver.ServerStatusRunning
)

const (
supportedHttpMethods = "GET,PUT,POST,DELETE,PATCH,HEAD,CONNECT,OPTIONS,TRACE"
defaultMethod = "ALL"
routeCacheDuration = time.Hour
ctxKeyForRequest gctx.StrKey = "gHttpRequestObject"
contentTypeXml = "text/xml"
contentTypeHtml = "text/html"
contentTypeJson = "application/json"
contentTypeJavascript = "application/javascript"
swaggerUIPackedPath = "/goframe/swaggerui"
responseHeaderTraceID = "Trace-ID"
responseHeaderContentLength = "Content-Length"
specialMethodNameInit = "Init"
specialMethodNameShut = "Shut"
specialMethodNameIndex = "Index"
defaultEndpointPort = 80
noPrintInternalRoute = "internalMiddlewareServerTracing"
supportedHttpMethods = "GET,PUT,POST,DELETE,PATCH,HEAD,CONNECT,OPTIONS,TRACE"
defaultMethod = "ALL"
routeCacheDuration = time.Hour
ctxKeyForRequest gctx.StrKey = "gHttpRequestObject"
contentTypeXml = "text/xml"
contentTypeHtml = "text/html"
contentTypeJson = "application/json"
contentTypeJavascript = "application/javascript"
swaggerUIPackedPath = "/goframe/swaggerui"
responseHeaderTraceID = "Trace-ID"
specialMethodNameInit = "Init"
specialMethodNameShut = "Shut"
specialMethodNameIndex = "Index"
defaultEndpointPort = 80
noPrintInternalRoute = "internalMiddlewareServerTracing"
)

const (
Expand Down
44 changes: 31 additions & 13 deletions net/ghttp/ghttp_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"sync"
"time"

"github.com/gogf/gf/v2/net/ghttp/internal/gracefulserver"
"github.com/olekukonko/tablewriter"

"github.com/gogf/gf/v2/container/garray"
Expand Down Expand Up @@ -97,7 +98,7 @@ func GetServer(name ...interface{}) *Server {
s := &Server{
instance: serverName,
plugins: make([]Plugin, 0),
servers: make([]*gracefulServer, 0),
servers: make([]*gracefulserver.Server, 0),
closeChan: make(chan struct{}, 10000),
serverCount: gtype.NewInt(),
statusHandlerMap: make(map[string][]HandlerFunc),
Expand Down Expand Up @@ -535,9 +536,9 @@ func (s *Server) startServer(fdMap listenerFdMap) {
if fd > 0 {
s.servers = append(s.servers, s.newGracefulServer(itemFunc, fd))
} else {
s.servers = append(s.servers, s.newGracefulServer(itemFunc))
s.servers = append(s.servers, s.newGracefulServer(itemFunc, 0))
}
s.servers[len(s.servers)-1].isHttps = true
s.servers[len(s.servers)-1].SetIsHttps(true)
}
}
// HTTP
Expand Down Expand Up @@ -570,7 +571,7 @@ func (s *Server) startServer(fdMap listenerFdMap) {
if fd > 0 {
s.servers = append(s.servers, s.newGracefulServer(itemFunc, fd))
} else {
s.servers = append(s.servers, s.newGracefulServer(itemFunc))
s.servers = append(s.servers, s.newGracefulServer(itemFunc, 0))
}
}
// Start listening asynchronously.
Expand All @@ -583,11 +584,11 @@ func (s *Server) startServer(fdMap listenerFdMap) {
wg.Wait()
}

func (s *Server) startGracefulServer(ctx context.Context, wg *sync.WaitGroup, server *gracefulServer) {
func (s *Server) startGracefulServer(ctx context.Context, wg *sync.WaitGroup, server *gracefulserver.Server) {
s.serverCount.Add(1)
var err error
// Create listener.
if server.isHttps {
if server.IsHttps() {
err = server.CreateListenerTLS(
s.config.HTTPSCertPath, s.config.HTTPSKeyPath, s.config.TLSConfig,
)
Expand Down Expand Up @@ -621,7 +622,7 @@ func (s *Server) Status() ServerStatus {
}
// If any underlying server is running, the server status is running.
for _, v := range s.servers {
if v.status.Val() == ServerStatusRunning {
if v.Status() == ServerStatusRunning {
return ServerStatusRunning
}
}
Expand All @@ -636,8 +637,8 @@ func (s *Server) getListenerFdMap() map[string]string {
"http": "",
}
for _, v := range s.servers {
str := v.address + "#" + gconv.String(v.Fd()) + ","
if v.isHttps {
str := v.GetAddress() + "#" + gconv.String(v.Fd()) + ","
if v.IsHttps() {
if len(m["https"]) > 0 {
m["https"] += ","
}
Expand All @@ -653,12 +654,29 @@ func (s *Server) getListenerFdMap() map[string]string {
}

// GetListenedPort retrieves and returns one port which is listened by current server.
// It returns the normal HTTP port in most priority if both HTTP and HTTPS are enabled.
func (s *Server) GetListenedPort() int {
ports := s.GetListenedPorts()
if len(ports) > 0 {
return ports[0]
for _, server := range s.servers {
if !server.IsHttps() {
return server.GetListenedPort()
}
}
for _, server := range s.servers {
if server.IsHttps() {
return server.GetListenedPort()
}
}
return -1
}

// GetListenedHTTPSPort retrieves and returns one port which is listened using TLS by current server.
func (s *Server) GetListenedHTTPSPort() int {
for _, server := range s.servers {
if server.IsHttps() {
return server.GetListenedPort()
}
}
return 0
return -1
}

// GetListenedPorts retrieves and returns the ports which are listened by current server.
Expand Down
2 changes: 1 addition & 1 deletion net/ghttp/ghttp_server_admin.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ func (s *Server) Shutdown() error {
// Only shut down current servers.
// It may have multiple underlying http servers.
for _, v := range s.servers {
v.shutdown(ctx)
v.Shutdown(ctx)
}
return nil
}
4 changes: 2 additions & 2 deletions net/ghttp/ghttp_server_admin_process.go
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ func shutdownWebServersGracefully(ctx context.Context, signal os.Signal) {
server := v.(*Server)
server.doServiceDeregister()
for _, s := range server.servers {
s.shutdown(ctx)
s.Shutdown(ctx)
}
}
})
Expand All @@ -279,7 +279,7 @@ func forceCloseWebServers(ctx context.Context) {
serverMapping.RLockFunc(func(m map[string]interface{}) {
for _, v := range m {
for _, s := range v.(*Server).servers {
s.close(ctx)
s.Close(ctx)
}
}
})
Expand Down
2 changes: 2 additions & 0 deletions net/ghttp/ghttp_server_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,7 @@ func (s *Server) SetAddr(address string) {
}

// SetPort sets the listening ports for the server.
// It uses random port if the port is 0.
// The listening ports can be multiple like: SetPort(80, 8080).
func (s *Server) SetPort(port ...int) {
if len(port) > 0 {
Expand All @@ -418,6 +419,7 @@ func (s *Server) SetHTTPSAddr(address string) {
}

// SetHTTPSPort sets the HTTPS listening ports for the server.
// It uses random port if the port is 0.
// The listening ports can be multiple like: SetHTTPSPort(443, 500).
func (s *Server) SetHTTPSPort(port ...int) {
if len(port) > 0 {
Expand Down
Loading
Loading