-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.go
More file actions
executable file
·299 lines (250 loc) · 8.94 KB
/
server.go
File metadata and controls
executable file
·299 lines (250 loc) · 8.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
package server
import (
"errors"
"net/http"
"path/filepath"
"sync"
)
// NOTE: circular dep prevents importing app — mirror the interface locally.
var _ serverInterface = (*ServerHandler)(nil)
type serverInterface interface {
StartServer(wg *sync.WaitGroup)
StopServer() error
RestartServer() error
NewFileEvent(fileName, extension, filePath, event string) error
UnobservedFiles() []string
SupportedExtensions() []string
Name() string
Label() string
Value() string
Change(v string)
RefreshUI()
MainInputFileRelativePath() string
RegisterRoutes(fn func(*http.ServeMux))
}
// Store defines the minimal interface for persistent storage
type Store interface {
Get(key string) (string, error)
Set(key, value string) error
}
// UI defines the minimal interface for UI interaction
type UI interface {
RefreshUI()
}
const (
StoreKeyExternalServer = "server_external_mode"
EnvKeyServerPort = "SERVER_PORT"
EnvKeyServerHttps = "SERVER_HTTPS"
)
// TestMode is a global flag to indicate the server is running in a test environment.
// This is used to disable aggressive cleanups and other disruptive behaviors.
var TestMode bool
type noopStore struct{}
func (noopStore) Get(string) (string, error) { return "", nil }
func (noopStore) Set(string, string) error { return nil }
type noopUI struct{}
func (noopUI) RefreshUI() {}
type ServerHandler struct {
*Config
mainFileExternalServer string // eg: main.server.go
strategy ServerStrategy
strategyMu sync.RWMutex // protects strategy field
executionInternal bool // true = embedded server (internal), false = external process
onLog func(message ...any)
openBrowserOnce sync.Once
// Internal route list
routes []func(*http.ServeMux)
}
type Config struct {
AppRootDir string // e.g., /home/user/project (application root directory)
SourceDir string // directory location of main.go e.g., src/cmd/appserver (relative to AppRootDir)
OutputDir string // compilation and execution directory e.g., deploy/appserver (relative to AppRootDir)
PublicDir string // default public dir for generated server (e.g., src/web/public)
MainInputFile string // main input file name (default: "main.go", can be "server.go", etc.)
ArgumentsForCompilingServer func() []string // e.g., []string{"-X 'main.version=v1.0.0'"}
ArgumentsToRunServer func() []string // e.g., []string{"dev"}
AppPort string // e.g., 6060
Https bool // true if HTTPS is enabled
DisableGlobalCleanup bool // If true, disables global cleanup in gorun during restarts
Logger func(message ...any) // Logger function
ExitChan chan bool // Global channel to signal shutdown
OpenBrowser func(port string, https bool)
Store Store // Persistent storage for modes
UI UI // UI for refresh notifications
OnExternalModeExecution func(isExternal bool) // Called before StartServer to notify mode change
GitIgnoreAdd func(entry string) error // Callback to add entries to .gitignore
}
// New creates a new ServerHandler with default configuration.
func New() *ServerHandler {
c := &Config{
AppRootDir: ".",
SourceDir: "web",
OutputDir: "web",
PublicDir: "web/public",
MainInputFile: "main.go",
AppPort: "6060",
Logger: nil,
ExitChan: make(chan bool),
ArgumentsForCompilingServer: func() []string { return nil },
ArgumentsToRunServer: func() []string { return nil },
OnExternalModeExecution: func(bool) {},
GitIgnoreAdd: func(string) error { return nil },
}
sh := &ServerHandler{
Config: c,
mainFileExternalServer: c.MainInputFile,
onLog: c.Logger,
routes: make([]func(*http.ServeMux), 0),
}
sh.Store = noopStore{}
sh.UI = noopUI{}
// Default to Internal Execution Mode
sh.executionInternal = true
sh.strategy = newInternalStrategy(sh)
return sh
}
// SetAppRootDir sets the application root directory
func (h *ServerHandler) SetAppRootDir(dir string) {
h.Config.AppRootDir = dir
}
// SetSourceDir sets the source directory relative to AppRootDir
func (h *ServerHandler) SetSourceDir(dir string) {
h.Config.SourceDir = dir
}
// SetOutputDir sets the output directory relative to AppRootDir
func (h *ServerHandler) SetOutputDir(dir string) {
h.Config.OutputDir = dir
}
// SetPublicDir sets the public directory
func (h *ServerHandler) SetPublicDir(dir string) *ServerHandler {
h.Config.PublicDir = dir
return h
}
// SetMainInputFile sets the main input file name
func (h *ServerHandler) SetMainInputFile(name string) {
h.Config.MainInputFile = name
h.mainFileExternalServer = name
}
// SetPort sets the server port
func (h *ServerHandler) SetPort(port string) {
h.Config.AppPort = port
}
// SetHTTPS enables or disables HTTPS
func (h *ServerHandler) SetHTTPS(enabled bool) *ServerHandler {
h.Config.Https = enabled
return h
}
// SetLogger sets the logger function
func (h *ServerHandler) SetLogger(fn func(...any)) *ServerHandler {
h.Config.Logger = fn
h.onLog = fn
return h
}
// SetExitChan sets the exit channel
func (h *ServerHandler) SetExitChan(ch chan bool) *ServerHandler {
h.Config.ExitChan = ch
return h
}
// SetOpenBrowser sets the open browser function
func (h *ServerHandler) SetOpenBrowser(fn func(port string, https bool)) *ServerHandler {
h.Config.OpenBrowser = fn
return h
}
// SetStore sets the persistent store
func (h *ServerHandler) SetStore(s Store) *ServerHandler {
if s != nil {
h.Config.Store = s
h.Store = s
}
return h
}
// SetUI sets the UI interface
func (h *ServerHandler) SetUI(ui UI) *ServerHandler {
if ui != nil {
h.Config.UI = ui
h.UI = ui
}
return h
}
// SetOnExternalModeExecution sets the callback for external mode execution
func (h *ServerHandler) SetOnExternalModeExecution(fn func(bool)) *ServerHandler {
h.Config.OnExternalModeExecution = fn
return h
}
// SetGitIgnoreAdd sets the callback to add entries to .gitignore
func (h *ServerHandler) SetGitIgnoreAdd(fn func(string) error) *ServerHandler {
h.Config.GitIgnoreAdd = fn
return h
}
// SetCompileArgs sets the arguments for compiling the server
func (h *ServerHandler) SetCompileArgs(fn func() []string) {
h.Config.ArgumentsForCompilingServer = fn
}
// SetRunArgs sets the arguments for running the server
func (h *ServerHandler) SetRunArgs(fn func() []string) {
h.Config.ArgumentsToRunServer = fn
}
// SetDisableGlobalCleanup enables or disables global cleanup
func (h *ServerHandler) SetDisableGlobalCleanup(disable bool) {
h.Config.DisableGlobalCleanup = disable
}
// RegisterRoutes appends fn to the internal route list.
// Call before StartServer.
func (h *ServerHandler) RegisterRoutes(fn func(*http.ServeMux)) {
h.routes = append(h.routes, fn)
}
func (h *ServerHandler) log(messages ...any) {
if h.onLog != nil {
h.onLog(messages...)
}
}
// MainInputFileRelativePath returns the path relative to AppRootDir (e.g., "src/cmd/appserver/main.go")
func (h *ServerHandler) MainInputFileRelativePath() string {
return filepath.Join(h.SourceDir, h.mainFileExternalServer)
}
func (h *ServerHandler) SupportedExtensions() []string {
return []string{".go"}
}
// UnobservedFiles returns the list of files that should not be tracked by file watchers
func (h *ServerHandler) UnobservedFiles() []string {
h.strategyMu.RLock()
defer h.strategyMu.RUnlock()
if !h.executionInternal {
if ext, ok := h.strategy.(*externalStrategy); ok {
return ext.goCompiler.UnobservedFiles()
}
}
return []string{}
}
// SetExternalServerMode switches between Internal and External server strategies.
// When switching to External, it also:
// 1. Generates server template files if they don't exist
// 2. Compiles the server
// 3. Starts the external process
func (h *ServerHandler) SetExternalServerMode(external bool) error {
h.strategyMu.Lock()
defer h.strategyMu.Unlock()
if external {
if h.executionInternal {
h.log("Switching to External Server Mode...")
// Generate template files if they don't exist
if err := h.generateServerFromEmbeddedMarkdown(); err != nil {
return err
}
// Stop current internal strategy
if err := h.strategy.Stop(); err != nil {
h.log("Warning stopping internal server:", err)
}
waitForPortFree(h.AppPort)
h.executionInternal = false
h.strategy = newExternalStrategy(h)
go h.strategy.Start(nil)
_ = h.Store.Set(StoreKeyExternalServer, "true")
}
} else {
if !h.executionInternal {
return errors.New("cannot switch back to Internal execution mode once External mode is active")
}
}
return nil
}