Skip to content

Commit

Permalink
fix(net/ghttp): occasional ci failed by unit testing cases using `gct…
Browse files Browse the repository at this point in the history
…p.GetFreePort` (#3982)
  • Loading branch information
gqcn authored Dec 10, 2024
1 parent 2e788be commit 38bffc7
Show file tree
Hide file tree
Showing 10 changed files with 472 additions and 361 deletions.
10 changes: 0 additions & 10 deletions .github/workflows/golangci-lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,6 @@ on:
- enhance/**
- fix/**
- feat/**
pull_request:
branches:
- master
- develop
- personal/**
- feature/**
- enhance/**
- fix/**
- feat/**

jobs:
golangci:
Expand Down Expand Up @@ -64,7 +55,6 @@ jobs:
-s "prefix(github.com/gogf/gf/example)" \
./
- name: Check for changes
id: check_changes
run: |
if [[ -n "$(git status --porcelain)" ]]; then
echo "HAS_CHANGES=true" >> $GITHUB_ENV
Expand Down
64 changes: 32 additions & 32 deletions net/ghttp/ghttp.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (
"github.com/gogf/gf/v2/container/gtype"
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/net/ghttp/internal/graceful"
"github.com/gogf/gf/v2/net/goai"
"github.com/gogf/gf/v2/net/gsvc"
"github.com/gogf/gf/v2/os/gcache"
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 []*graceful.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 @@ -69,7 +70,7 @@ type (
Method string // Handler method name.
Route string // Route URI.
Priority int // Just for reference.
IsServiceHandler bool // Is service handler.
IsServiceHandler bool // Is a service handler.
}

// HandlerFunc is request handler function.
Expand Down Expand Up @@ -127,42 +128,41 @@ type (

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

const (
HeaderXUrlPath = "x-url-path" // Used for custom route handler, which does not change URL.Path.
HookBeforeServe HookName = "HOOK_BEFORE_SERVE" // Hook handler before route handler/file serving.
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"
HeaderXUrlPath = "x-url-path" // Used for custom route handler, which does not change URL.Path.
HookBeforeServe HookName = "HOOK_BEFORE_SERVE" // Hook handler before route handler/file serving.
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.
DefaultServerName = "default"
DefaultDomainName = "default"
HandlerTypeHandler HandlerType = "handler"
HandlerTypeObject HandlerType = "object"
HandlerTypeMiddleware HandlerType = "middleware"
HandlerTypeHook HandlerType = "hook"
ServerStatusStopped = graceful.ServerStatusStopped
ServerStatusRunning = graceful.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 @@ -26,6 +26,7 @@ import (
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/internal/intlog"
"github.com/gogf/gf/v2/net/ghttp/internal/graceful"
"github.com/gogf/gf/v2/net/ghttp/internal/swaggerui"
"github.com/gogf/gf/v2/net/goai"
"github.com/gogf/gf/v2/net/gsvc"
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([]*graceful.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 *graceful.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

0 comments on commit 38bffc7

Please sign in to comment.