Skip to content

Commit fcd6021

Browse files
committed
cd cmd/caddy && go run main.go run to print info to see detail. and caddyabc module
1 parent d85cc2e commit fcd6021

File tree

7 files changed

+205
-0
lines changed

7 files changed

+205
-0
lines changed

admin.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -270,11 +270,14 @@ func (admin *AdminConfig) newAdminHandler(addr NetworkAddress, remote bool) admi
270270
for _, m := range GetModules("admin.api") {
271271
router := m.New().(AdminRouter)
272272
handlerLabel := m.ID.Name()
273+
fmt.Println("[newAdminHandler] handlerLabel is", handlerLabel)
273274
for _, route := range router.Routes() {
275+
fmt.Println("[newAdminHandler] route.Pattern is", route.Pattern)
274276
addRoute(route.Pattern, handlerLabel, route.Handler)
275277
}
276278
admin.routers = append(admin.routers, router)
277279
}
280+
fmt.Println("[newAdminHandler] admin.routers is", admin.routers)
278281

279282
return muxWrap
280283
}
@@ -382,6 +385,7 @@ func (admin AdminConfig) allowedOrigins(addr NetworkAddress) []*url.URL {
382385
// that there is always an admin server (unless it is explicitly
383386
// configured to be disabled).
384387
func replaceLocalAdminServer(cfg *Config) error {
388+
fmt.Println("[replaceLocalAdminServer] Into")
385389
// always* be sure to close down the old admin endpoint
386390
// as gracefully as possible, even if the new one is
387391
// disabled -- careful to use reference to the current
@@ -423,7 +427,10 @@ func replaceLocalAdminServer(cfg *Config) error {
423427
return err
424428
}
425429

430+
fmt.Println("[replaceLocalAdminServer] newAdminHandler() into")
426431
handler := cfg.Admin.newAdminHandler(addr, false)
432+
fmt.Println("[replaceLocalAdminServer] newAdminHandler() out")
433+
fmt.Println("-----------")
427434

428435
ln, err := addr.Listen(context.TODO(), 0, net.ListenConfig{})
429436
if err != nil {
@@ -461,6 +468,9 @@ func replaceLocalAdminServer(cfg *Config) error {
461468
zap.String("address", addr.String()))
462469
}
463470

471+
fmt.Println("[replaceLocalAdminServer] Out")
472+
fmt.Println("-----------")
473+
464474
return nil
465475
}
466476

@@ -1131,6 +1141,17 @@ func unsyncedConfigAccess(method, path string, body []byte, out io.Writer) error
11311141

11321142
var ptr any = rawCfg
11331143

1144+
fmt.Println("=============")
1145+
fmt.Println("[unsyncedConfigAccess] Before traverseLoop:");
1146+
fmt.Println("body:", string(body)) // 配置的完整json字符串
1147+
fmt.Println("method:", method) // POST
1148+
fmt.Println("parts:", parts) // [config]
1149+
fmt.Println("len(parts):", len(parts)) // 1
1150+
fmt.Println("ptr:", ptr) // map[config:<nil>]
1151+
fmt.Println("rawCfg:", rawCfg) // map[config:<nil>]
1152+
fmt.Println("val:", val) // 配置的完整json对象(GO的数据结构)
1153+
fmt.Println("=============")
1154+
11341155
traverseLoop:
11351156
for i, part := range parts {
11361157
switch v := ptr.(type) {
@@ -1206,6 +1227,10 @@ traverseLoop:
12061227
v[part] = append(arr, val)
12071228
}
12081229
} else {
1230+
fmt.Println("[unsyncedConfigAccess] In traverseLoop:");
1231+
fmt.Println("arr,ok:", arr, ok)
1232+
fmt.Println("val:", val)
1233+
fmt.Println("=============")
12091234
v[part] = val
12101235
}
12111236
case http.MethodPut:
@@ -1262,6 +1287,12 @@ traverseLoop:
12621287
}
12631288
}
12641289

1290+
fmt.Println("[unsyncedConfigAccess] After traverseLoop:");
1291+
fmt.Println("ptr:", ptr)
1292+
fmt.Println("=============")
1293+
fmt.Println("rawCfg:", rawCfg) // 此函数最终是为了,填充成 map["config":val] 这种形式
1294+
fmt.Println("=============")
1295+
12651296
return nil
12661297
}
12671298

caddy.go

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -315,6 +315,8 @@ func indexConfigObjects(ptr any, configPath string, index map[string]string) err
315315
// allowPersist is false, it will not be persisted to disk,
316316
// even if it is configured to.
317317
func unsyncedDecodeAndRun(cfgJSON []byte, allowPersist bool) error {
318+
fmt.Println("[unsyncedDecodeAndRun] Into")
319+
318320
// remove any @id fields from the JSON, which would cause
319321
// loading to break since the field wouldn't be recognized
320322
strippedCfgJSON := RemoveMetaFields(cfgJSON)
@@ -339,21 +341,31 @@ func unsyncedDecodeAndRun(cfgJSON []byte, allowPersist bool) error {
339341
return fmt.Errorf("recursive config loading detected: pulled configs cannot pull other configs without positive load_delay")
340342
}
341343

344+
fmt.Println("[unsyncedDecodeAndRun] before run()")
345+
342346
// run the new config and start all its apps
343347
ctx, err := run(newCfg, true)
344348
if err != nil {
345349
return err
346350
}
347351

352+
fmt.Println("[unsyncedDecodeAndRun] after run()")
353+
fmt.Println("[unsyncedDecodeAndRun] newCfg:", newCfg)
354+
348355
// swap old context (including its config) with the new one
349356
currentCtxMu.Lock()
350357
oldCtx := currentCtx
351358
currentCtx = ctx
352359
currentCtxMu.Unlock()
353360

361+
fmt.Println("[unsyncedDecodeAndRun] before unsyncedStop(), oldCtx:", oldCtx)
362+
354363
// Stop, Cleanup each old app
355364
unsyncedStop(oldCtx)
356365

366+
fmt.Println("[unsyncedDecodeAndRun] after unsyncedStop()")
367+
fmt.Println("=============")
368+
357369
// autosave a non-nil config, if not disabled
358370
if allowPersist &&
359371
newCfg != nil &&
@@ -379,6 +391,9 @@ func unsyncedDecodeAndRun(cfgJSON []byte, allowPersist bool) error {
379391
}
380392
}
381393

394+
fmt.Println("[unsyncedDecodeAndRun] after autosave config")
395+
fmt.Println("=============/")
396+
382397
return nil
383398
}
384399

@@ -397,7 +412,22 @@ func unsyncedDecodeAndRun(cfgJSON []byte, allowPersist bool) error {
397412
// will want to use Run instead, which also
398413
// updates the config's raw state.
399414
func run(newCfg *Config, start bool) (Context, error) {
415+
fmt.Println("----------")
416+
fmt.Println("[run] Into")
417+
418+
fmt.Println("----------")
419+
fmt.Println("Before provisionContext()")
420+
fmt.Println("----------")
421+
400422
ctx, err := provisionContext(newCfg, start)
423+
424+
fmt.Println("----------")
425+
fmt.Println("After provisionContext()")
426+
fmt.Println("----------")
427+
428+
// {context.Background.WithCancel map[events:[0xc0007039e0] http:[0xc0003f86c0] http.matchers.host:[0xc0002a4240] tls:[0xc0000cfe00]] 0xc0003a08a0 [] [] []}
429+
fmt.Println("[run] ctx:", ctx)
430+
401431
if err != nil {
402432
return ctx, err
403433
}
@@ -413,11 +443,18 @@ func run(newCfg *Config, start bool) (Context, error) {
413443
return ctx, err
414444
}
415445

446+
fmt.Println("[run] provisionAdminRouters after")
447+
fmt.Println("----------")
448+
416449
// Start
417450
err = func() error {
418451
started := make([]string, 0, len(ctx.cfg.apps))
419452
for name, a := range ctx.cfg.apps {
420453
err := a.Start()
454+
455+
fmt.Println("[run]", name, "Started")
456+
fmt.Println("----------/")
457+
421458
if err != nil {
422459
// an app failed to start, so we need to stop
423460
// all other apps that were already started
@@ -438,6 +475,9 @@ func run(newCfg *Config, start bool) (Context, error) {
438475
return ctx, err
439476
}
440477

478+
fmt.Println("[run] Before finishSettingUp")
479+
fmt.Println("[run] ctx.cfg :", ctx.cfg)
480+
441481
// now that the user's config is running, finish setting up anything else,
442482
// such as remote admin endpoint, config loader, etc.
443483
return ctx, finishSettingUp(ctx, ctx.cfg)
@@ -509,6 +549,8 @@ func provisionContext(newCfg *Config, replaceAdminServer bool) (Context, error)
509549
// prepare the new config for use
510550
newCfg.apps = make(map[string]App)
511551

552+
fmt.Println("[provisionContext] set up global storage Before")
553+
512554
// set up global storage and make it CertMagic's default storage, too
513555
err = func() error {
514556
if newCfg.StorageRaw != nil {
@@ -534,15 +576,22 @@ func provisionContext(newCfg *Config, replaceAdminServer bool) (Context, error)
534576
return ctx, err
535577
}
536578

579+
fmt.Println("[provisionContext] set up global storage After")
580+
fmt.Println("[provisionContext] Load and Provision each app and their submodules Before")
581+
537582
// Load and Provision each app and their submodules
538583
err = func() error {
539584
for appName := range newCfg.AppsRaw {
585+
fmt.Println("appName:", appName)
540586
if _, err := ctx.App(appName); err != nil {
541587
return err
542588
}
543589
}
544590
return nil
545591
}()
592+
593+
fmt.Println("[provisionContext] Load and Provision each app and their submodules After")
594+
546595
return ctx, err
547596
}
548597

@@ -557,6 +606,9 @@ func ProvisionContext(newCfg *Config) (Context, error) {
557606

558607
// finishSettingUp should be run after all apps have successfully started.
559608
func finishSettingUp(ctx Context, cfg *Config) error {
609+
fmt.Println("----====----")
610+
fmt.Println("[finishSettingUp] Into")
611+
560612
// establish this server's identity (only after apps are loaded
561613
// so that cert management of this endpoint doesn't prevent user's
562614
// servers from starting which likely also use HTTP/HTTPS ports;
@@ -566,14 +618,23 @@ func finishSettingUp(ctx Context, cfg *Config) error {
566618
return fmt.Errorf("provisioning remote admin endpoint: %v", err)
567619
}
568620

621+
fmt.Println("[finishSettingUp] replaceRemoteAdminServer before")
622+
569623
// replace any remote admin endpoint
570624
err = replaceRemoteAdminServer(ctx, cfg)
571625
if err != nil {
572626
return fmt.Errorf("provisioning remote admin endpoint: %v", err)
573627
}
574628

629+
fmt.Println("[finishSettingUp] replaceRemoteAdminServer after")
630+
fmt.Println("[finishSettingUp] The cfg:", cfg)
631+
fmt.Println("[finishSettingUp] cfg.Admin:", cfg.Admin)
632+
fmt.Println("[finishSettingUp] cfg.Admin.Config:", cfg.Admin.Config)
633+
575634
// if dynamic config is requested, set that up and run it
576635
if cfg != nil && cfg.Admin != nil && cfg.Admin.Config != nil && cfg.Admin.Config.LoadRaw != nil {
636+
fmt.Println("[finishSettingUp] cfg.Admin.Config.LoadDelay =", cfg.Admin.Config.LoadDelay)
637+
577638
val, err := ctx.LoadModule(cfg.Admin.Config, "LoadRaw")
578639
if err != nil {
579640
return fmt.Errorf("loading config loader module: %s", err)
@@ -639,6 +700,8 @@ func finishSettingUp(ctx Context, cfg *Config) error {
639700
}
640701
}
641702

703+
fmt.Println("----====----/")
704+
642705
return nil
643706
}
644707

caddyabc/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# caddyabc
2+
3+
A custom module for plugged in.

caddyabc/a.go

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package caddyabc
2+
3+
import (
4+
"github.com/caddyserver/caddy/v2"
5+
)
6+
7+
func init() {
8+
caddy.Log().Info("init() caddyabc")
9+
caddy.RegisterModule(A{})
10+
caddy.RegisterModule(B{})
11+
}
12+
13+
// A只是一个例子;可以是你自己的类型
14+
type A struct {
15+
MyField string `json:"my_field,omitempty"`
16+
Number int `json:"number,omitempty"`
17+
}
18+
19+
// 通过CaddyModule方法返回Caddy模块的信息
20+
func (A) CaddyModule() caddy.ModuleInfo {
21+
caddy.Log().Info("into A CaddyModule()")
22+
return caddy.ModuleInfo{
23+
ID: "caddy.abc.a", // namespace is caddy.abc, module_name is a
24+
New: func() caddy.Module { return new(A) },
25+
}
26+
}
27+
28+
func (a *A) Start() error {
29+
caddy.Log().Info("A is started")
30+
31+
return nil
32+
}
33+
34+
// Provision sets up the module.
35+
func (g *A) Provision(ctx caddy.Context) error {
36+
// TODO: set up the module
37+
38+
// ctx.Logger() is a *zap.Logger
39+
ctx.Logger().Info("into A Provision()")
40+
return nil
41+
}
42+
43+
// Validate validates that the module has a usable config.
44+
func (g A) Validate() error {
45+
// TODO: validate the module's setup
46+
return nil
47+
}
48+
49+
// Interface guards
50+
var (
51+
_ caddy.Provisioner = (*A)(nil)
52+
_ caddy.Validator = (*A)(nil)
53+
)

caddyabc/b.go

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package caddyabc
2+
3+
import (
4+
"github.com/caddyserver/caddy/v2"
5+
)
6+
7+
// B只是一个例子;可以是你自己的类型
8+
type B struct {
9+
MyField string `json:"my_field,omitempty"`
10+
Number int `json:"number,omitempty"`
11+
}
12+
13+
// 通过CaddyModule方法返回Caddy模块的信息
14+
func (B) CaddyModule() caddy.ModuleInfo {
15+
caddy.Log().Info("into B CaddyModule()")
16+
return caddy.ModuleInfo{
17+
ID: "caddy.abc.b", // namespace is caddy.abc, module_name is b
18+
New: func() caddy.Module { return new(B) },
19+
}
20+
}
21+
22+
func (b *B) Start() error {
23+
caddy.Log().Info("B is started")
24+
25+
return nil
26+
}
27+
28+
29+
// Provision sets up the module.
30+
func (g *B) Provision(ctx caddy.Context) error {
31+
// TODO: set up the module
32+
33+
// ctx.Logger() is a *zap.Logger
34+
ctx.Logger().Info("into A Provision()")
35+
return nil
36+
}
37+
38+
// Validate validates that the module has a usable config.
39+
func (g B) Validate() error {
40+
// TODO: validate the module's setup
41+
return nil
42+
}
43+
44+
// Interface guards
45+
var (
46+
_ caddy.Provisioner = (*B)(nil)
47+
_ caddy.Validator = (*B)(nil)
48+
)
49+

cmd/caddy/main.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@ import (
3232
caddycmd "github.com/caddyserver/caddy/v2/cmd"
3333

3434
// plug in Caddy modules here
35+
_ "github.com/caddyserver/caddy/v2/caddyabc"
36+
3537
_ "github.com/caddyserver/caddy/v2/modules/standard"
3638
)
3739

cmd/main.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,10 @@ func loadConfigWithLogger(logger *zap.Logger, configFile, adapterName string) ([
214214
return nil, "", fmt.Errorf("adapting config using %s: %v", adapterName, err)
215215
}
216216
logger.Info("adapted config to JSON", zap.String("adapter", adapterName))
217+
// logger.Info(string(config))
218+
// logger.Info(string(configFile))
219+
// logger.Info(string(adaptedConfig))
220+
// os.Exit(1)
217221
for _, warn := range warnings {
218222
msg := warn.Message
219223
if warn.Directive != "" {

0 commit comments

Comments
 (0)