Skip to content

Commit 87e1160

Browse files
committed
add Terminate method to fake server
1 parent 91f6922 commit 87e1160

File tree

1 file changed

+36
-1
lines changed

1 file changed

+36
-1
lines changed

framework/components/fake/fake.go

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
package fake
22

33
import (
4+
"context"
45
"fmt"
6+
"net/http"
57
"os"
68
"regexp"
79

@@ -28,16 +30,31 @@ type Output struct {
2830

2931
var (
3032
Service *gin.Engine
33+
server *http.Server
3134
validMethod = regexp.MustCompile("GET|POST|PATCH|PUT|DELETE")
3235
)
3336

3437
// NewFakeDataProvider creates new fake data provider
3538
func NewFakeDataProvider(in *Input) (*Output, error) {
39+
if server != nil {
40+
return nil, fmt.Errorf("fake service is already running, call TerminateService first")
41+
}
42+
3643
Service = gin.Default()
3744
Service.Use(recordMiddleware())
45+
46+
server = &http.Server{
47+
Addr: fmt.Sprintf(":%d", in.Port),
48+
Handler: Service,
49+
}
50+
3851
go func() {
39-
_ = Service.Run(fmt.Sprintf(":%d", in.Port))
52+
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
53+
// Log error but don't panic - server might be intentionally shut down
54+
fmt.Printf("Fake service error: %v\n", err)
55+
}
4056
}()
57+
4158
out := &Output{
4259
BaseURLHost: fmt.Sprintf("http://localhost:%d", in.Port),
4360
BaseURLDocker: fmt.Sprintf("%s:%d", framework.HostDockerInternal(), in.Port),
@@ -81,6 +98,24 @@ func JSON(method, path string, response map[string]any, statusCode int) error {
8198
return nil
8299
}
83100

101+
// TerminateService synchronously shuts down the fake service
102+
func TerminateService(ctx context.Context) error {
103+
if server == nil {
104+
return nil
105+
}
106+
if err := server.Shutdown(ctx); err != nil {
107+
return fmt.Errorf("failed to shutdown fake service gracefully: %w", err)
108+
}
109+
Service = nil
110+
server = nil
111+
return nil
112+
}
113+
114+
// IsServiceRunning returns true if the fake service is currently running
115+
func IsServiceRunning() bool {
116+
return server != nil && Service != nil
117+
}
118+
84119
// HostDockerInternal returns host.docker.internal that works both locally and in GHA
85120
func HostDockerInternal() string {
86121
if os.Getenv("CI") == "true" {

0 commit comments

Comments
 (0)