Skip to content

Commit 38bffc7

Browse files
authored
fix(net/ghttp): occasional ci failed by unit testing cases using gctp.GetFreePort (#3982)
1 parent 2e788be commit 38bffc7

10 files changed

+472
-361
lines changed

.github/workflows/golangci-lint.yml

-10
Original file line numberDiff line numberDiff line change
@@ -15,15 +15,6 @@ on:
1515
- enhance/**
1616
- fix/**
1717
- feat/**
18-
pull_request:
19-
branches:
20-
- master
21-
- develop
22-
- personal/**
23-
- feature/**
24-
- enhance/**
25-
- fix/**
26-
- feat/**
2718

2819
jobs:
2920
golangci:
@@ -64,7 +55,6 @@ jobs:
6455
-s "prefix(github.com/gogf/gf/example)" \
6556
./
6657
- name: Check for changes
67-
id: check_changes
6858
run: |
6959
if [[ -n "$(git status --porcelain)" ]]; then
7060
echo "HAS_CHANGES=true" >> $GITHUB_ENV

net/ghttp/ghttp.go

+32-32
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import (
1919
"github.com/gogf/gf/v2/container/gtype"
2020
"github.com/gogf/gf/v2/errors/gcode"
2121
"github.com/gogf/gf/v2/errors/gerror"
22+
"github.com/gogf/gf/v2/net/ghttp/internal/graceful"
2223
"github.com/gogf/gf/v2/net/goai"
2324
"github.com/gogf/gf/v2/net/gsvc"
2425
"github.com/gogf/gf/v2/os/gcache"
@@ -34,7 +35,7 @@ type (
3435
instance string // Instance name of current HTTP server.
3536
config ServerConfig // Server configuration.
3637
plugins []Plugin // Plugin array to extend server functionality.
37-
servers []*gracefulServer // Underlying http.Server array.
38+
servers []*graceful.Server // Underlying http.Server array.
3839
serverCount *gtype.Int // Underlying http.Server number for internal usage.
3940
closeChan chan struct{} // Used for underlying server closing event notification.
4041
serveTree map[string]interface{} // The route maps tree.
@@ -69,7 +70,7 @@ type (
6970
Method string // Handler method name.
7071
Route string // Route URI.
7172
Priority int // Just for reference.
72-
IsServiceHandler bool // Is service handler.
73+
IsServiceHandler bool // Is a service handler.
7374
}
7475

7576
// HandlerFunc is request handler function.
@@ -127,42 +128,41 @@ type (
127128

128129
const (
129130
// FreePortAddress marks the server listens using random free port.
130-
FreePortAddress = ":0"
131+
FreePortAddress = graceful.FreePortAddress
131132
)
132133

133134
const (
134-
HeaderXUrlPath = "x-url-path" // Used for custom route handler, which does not change URL.Path.
135-
HookBeforeServe HookName = "HOOK_BEFORE_SERVE" // Hook handler before route handler/file serving.
136-
HookAfterServe HookName = "HOOK_AFTER_SERVE" // Hook handler after route handler/file serving.
137-
HookBeforeOutput HookName = "HOOK_BEFORE_OUTPUT" // Hook handler before response output.
138-
HookAfterOutput HookName = "HOOK_AFTER_OUTPUT" // Hook handler after response output.
139-
ServerStatusStopped ServerStatus = 0
140-
ServerStatusRunning ServerStatus = 1
141-
DefaultServerName = "default"
142-
DefaultDomainName = "default"
143-
HandlerTypeHandler HandlerType = "handler"
144-
HandlerTypeObject HandlerType = "object"
145-
HandlerTypeMiddleware HandlerType = "middleware"
146-
HandlerTypeHook HandlerType = "hook"
135+
HeaderXUrlPath = "x-url-path" // Used for custom route handler, which does not change URL.Path.
136+
HookBeforeServe HookName = "HOOK_BEFORE_SERVE" // Hook handler before route handler/file serving.
137+
HookAfterServe HookName = "HOOK_AFTER_SERVE" // Hook handler after route handler/file serving.
138+
HookBeforeOutput HookName = "HOOK_BEFORE_OUTPUT" // Hook handler before response output.
139+
HookAfterOutput HookName = "HOOK_AFTER_OUTPUT" // Hook handler after response output.
140+
DefaultServerName = "default"
141+
DefaultDomainName = "default"
142+
HandlerTypeHandler HandlerType = "handler"
143+
HandlerTypeObject HandlerType = "object"
144+
HandlerTypeMiddleware HandlerType = "middleware"
145+
HandlerTypeHook HandlerType = "hook"
146+
ServerStatusStopped = graceful.ServerStatusStopped
147+
ServerStatusRunning = graceful.ServerStatusRunning
147148
)
148149

149150
const (
150-
supportedHttpMethods = "GET,PUT,POST,DELETE,PATCH,HEAD,CONNECT,OPTIONS,TRACE"
151-
defaultMethod = "ALL"
152-
routeCacheDuration = time.Hour
153-
ctxKeyForRequest gctx.StrKey = "gHttpRequestObject"
154-
contentTypeXml = "text/xml"
155-
contentTypeHtml = "text/html"
156-
contentTypeJson = "application/json"
157-
contentTypeJavascript = "application/javascript"
158-
swaggerUIPackedPath = "/goframe/swaggerui"
159-
responseHeaderTraceID = "Trace-ID"
160-
responseHeaderContentLength = "Content-Length"
161-
specialMethodNameInit = "Init"
162-
specialMethodNameShut = "Shut"
163-
specialMethodNameIndex = "Index"
164-
defaultEndpointPort = 80
165-
noPrintInternalRoute = "internalMiddlewareServerTracing"
151+
supportedHttpMethods = "GET,PUT,POST,DELETE,PATCH,HEAD,CONNECT,OPTIONS,TRACE"
152+
defaultMethod = "ALL"
153+
routeCacheDuration = time.Hour
154+
ctxKeyForRequest gctx.StrKey = "gHttpRequestObject"
155+
contentTypeXml = "text/xml"
156+
contentTypeHtml = "text/html"
157+
contentTypeJson = "application/json"
158+
contentTypeJavascript = "application/javascript"
159+
swaggerUIPackedPath = "/goframe/swaggerui"
160+
responseHeaderTraceID = "Trace-ID"
161+
specialMethodNameInit = "Init"
162+
specialMethodNameShut = "Shut"
163+
specialMethodNameIndex = "Index"
164+
defaultEndpointPort = 80
165+
noPrintInternalRoute = "internalMiddlewareServerTracing"
166166
)
167167

168168
const (

net/ghttp/ghttp_server.go

+31-13
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import (
2626
"github.com/gogf/gf/v2/errors/gcode"
2727
"github.com/gogf/gf/v2/errors/gerror"
2828
"github.com/gogf/gf/v2/internal/intlog"
29+
"github.com/gogf/gf/v2/net/ghttp/internal/graceful"
2930
"github.com/gogf/gf/v2/net/ghttp/internal/swaggerui"
3031
"github.com/gogf/gf/v2/net/goai"
3132
"github.com/gogf/gf/v2/net/gsvc"
@@ -97,7 +98,7 @@ func GetServer(name ...interface{}) *Server {
9798
s := &Server{
9899
instance: serverName,
99100
plugins: make([]Plugin, 0),
100-
servers: make([]*gracefulServer, 0),
101+
servers: make([]*graceful.Server, 0),
101102
closeChan: make(chan struct{}, 10000),
102103
serverCount: gtype.NewInt(),
103104
statusHandlerMap: make(map[string][]HandlerFunc),
@@ -535,9 +536,9 @@ func (s *Server) startServer(fdMap listenerFdMap) {
535536
if fd > 0 {
536537
s.servers = append(s.servers, s.newGracefulServer(itemFunc, fd))
537538
} else {
538-
s.servers = append(s.servers, s.newGracefulServer(itemFunc))
539+
s.servers = append(s.servers, s.newGracefulServer(itemFunc, 0))
539540
}
540-
s.servers[len(s.servers)-1].isHttps = true
541+
s.servers[len(s.servers)-1].SetIsHttps(true)
541542
}
542543
}
543544
// HTTP
@@ -570,7 +571,7 @@ func (s *Server) startServer(fdMap listenerFdMap) {
570571
if fd > 0 {
571572
s.servers = append(s.servers, s.newGracefulServer(itemFunc, fd))
572573
} else {
573-
s.servers = append(s.servers, s.newGracefulServer(itemFunc))
574+
s.servers = append(s.servers, s.newGracefulServer(itemFunc, 0))
574575
}
575576
}
576577
// Start listening asynchronously.
@@ -583,11 +584,11 @@ func (s *Server) startServer(fdMap listenerFdMap) {
583584
wg.Wait()
584585
}
585586

586-
func (s *Server) startGracefulServer(ctx context.Context, wg *sync.WaitGroup, server *gracefulServer) {
587+
func (s *Server) startGracefulServer(ctx context.Context, wg *sync.WaitGroup, server *graceful.Server) {
587588
s.serverCount.Add(1)
588589
var err error
589590
// Create listener.
590-
if server.isHttps {
591+
if server.IsHttps() {
591592
err = server.CreateListenerTLS(
592593
s.config.HTTPSCertPath, s.config.HTTPSKeyPath, s.config.TLSConfig,
593594
)
@@ -621,7 +622,7 @@ func (s *Server) Status() ServerStatus {
621622
}
622623
// If any underlying server is running, the server status is running.
623624
for _, v := range s.servers {
624-
if v.status.Val() == ServerStatusRunning {
625+
if v.Status() == ServerStatusRunning {
625626
return ServerStatusRunning
626627
}
627628
}
@@ -636,8 +637,8 @@ func (s *Server) getListenerFdMap() map[string]string {
636637
"http": "",
637638
}
638639
for _, v := range s.servers {
639-
str := v.address + "#" + gconv.String(v.Fd()) + ","
640-
if v.isHttps {
640+
str := v.GetAddress() + "#" + gconv.String(v.Fd()) + ","
641+
if v.IsHttps() {
641642
if len(m["https"]) > 0 {
642643
m["https"] += ","
643644
}
@@ -653,12 +654,29 @@ func (s *Server) getListenerFdMap() map[string]string {
653654
}
654655

655656
// GetListenedPort retrieves and returns one port which is listened by current server.
657+
// It returns the normal HTTP port in most priority if both HTTP and HTTPS are enabled.
656658
func (s *Server) GetListenedPort() int {
657-
ports := s.GetListenedPorts()
658-
if len(ports) > 0 {
659-
return ports[0]
659+
for _, server := range s.servers {
660+
if !server.IsHttps() {
661+
return server.GetListenedPort()
662+
}
663+
}
664+
for _, server := range s.servers {
665+
if server.IsHttps() {
666+
return server.GetListenedPort()
667+
}
668+
}
669+
return -1
670+
}
671+
672+
// GetListenedHTTPSPort retrieves and returns one port which is listened using TLS by current server.
673+
func (s *Server) GetListenedHTTPSPort() int {
674+
for _, server := range s.servers {
675+
if server.IsHttps() {
676+
return server.GetListenedPort()
677+
}
660678
}
661-
return 0
679+
return -1
662680
}
663681

664682
// GetListenedPorts retrieves and returns the ports which are listened by current server.

net/ghttp/ghttp_server_admin.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ func (s *Server) Shutdown() error {
9595
// Only shut down current servers.
9696
// It may have multiple underlying http servers.
9797
for _, v := range s.servers {
98-
v.shutdown(ctx)
98+
v.Shutdown(ctx)
9999
}
100100
return nil
101101
}

net/ghttp/ghttp_server_admin_process.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -268,7 +268,7 @@ func shutdownWebServersGracefully(ctx context.Context, signal os.Signal) {
268268
server := v.(*Server)
269269
server.doServiceDeregister()
270270
for _, s := range server.servers {
271-
s.shutdown(ctx)
271+
s.Shutdown(ctx)
272272
}
273273
}
274274
})
@@ -279,7 +279,7 @@ func forceCloseWebServers(ctx context.Context) {
279279
serverMapping.RLockFunc(func(m map[string]interface{}) {
280280
for _, v := range m {
281281
for _, s := range v.(*Server).servers {
282-
s.close(ctx)
282+
s.Close(ctx)
283283
}
284284
}
285285
})

net/ghttp/ghttp_server_config.go

+2
Original file line numberDiff line numberDiff line change
@@ -399,6 +399,7 @@ func (s *Server) SetAddr(address string) {
399399
}
400400

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

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

0 commit comments

Comments
 (0)