funcRegisterModule(instance Module) { mod := instance.CaddyModule()
if mod.ID == "" { panic("module ID missing") } if mod.ID == "caddy" || mod.ID == "admin" { panic(fmt.Sprintf("module ID '%s' is reserved", mod.ID)) } if mod.New == nil { panic("missing ModuleInfo.New") } if val := mod.New(); val == nil { panic("ModuleInfo.New must return a non-nil module instance") }
modulesMu.Lock() defer modulesMu.Unlock()
if _, ok := modules[string(mod.ID)]; ok { panic(fmt.Sprintf("module already registered: %s", mod.ID)) } modules[string(mod.ID)] = mod }
只要插件实现了对应的接口,并注册上去,caddy 会通过下面的方法获取:
1 2 3 4 5 6 7 8 9 10
// GetModule returns module information from its ID (full name). funcGetModule(name string) (ModuleInfo, error) { modulesMu.RLock() defer modulesMu.RUnlock() m, ok := modules[name] if !ok { return ModuleInfo{}, fmt.Errorf("module not registered: %s", name) } return m, nil }
// 转换为对应接口类型 unm, ok := mod.New().(caddyfile.Unmarshaler) if !ok { return fmt.Errorf("matcher module '%s' is not a Caddyfile unmarshaler", matcherName) }