英文:
How to provide additional data to a go handler
问题
早上好,
将附加参数传递给Go处理程序的方法相当模糊。因此,我在这里总结了我的问题:
假设我有一个Windows服务,它读取一个配置文件并启动一个SMTP监听器:
func (m *myservice) Execute(args []string, r <-chan svc.ChangeRequest, changes chan<- svc.Status) (ssec bool, errno uint32) {
Configurationx := loadConfiguration()
log.Println("test : Foo is : " + Configurationx.foo) // << ok
go func() {
smtpd.ListenAndServe("127.0.0.1:25", mailHandler, "myServer", "")
}()
// 这里没有问题
changes <- svc.Status{State: svc.Running, Accepts: cmdsAccepted}
loop:
// < service loop that is skipped ;>
}
以下邮件处理程序工作正常:
func mailHandler(origin net.Addr, from string, to []string, data []byte) error {
// 处理传入的邮件
}
但是,如果我希望它在处理邮件时使用变量"Configurationx"中的配置信息,最好的方法是什么?在mailHandler内部,"Configurationx"是不可访问的。
谢谢你的帮助。
英文:
Good Morning,
The way to pass additional parameters to a go handler is quite fuzzy. I thus summarize here my problem:
Considering I have a windows service that read a config file and start a smtp listener :
func (m *myservice) Execute(args []string, r <-chan svc.ChangeRequest, changes chan<- svc.Status) (ssec bool, errno uint32) {
Configurationx := loadConfiguration();
log.Println("test : Foo is : "+Configurationx.foo ) //<< ok
go func( ) {
smtpd.ListenAndServe("127.0.0.1:25", mailHandler, "myServer", "")
}();
// Here below there is no problem
changes <- svc.Status{State: svc.Running, Accepts: cmdsAccepted}
loop:
//< service loop that is skipped ;>
}
The following mail handler is working good
func mailHandler(origin net.Addr, from string, to []string, data []byte) error {
// the handler recieve the incoming mails
}
But if I want it to handle mail using configuration information from the var "Configurationx" , what is the best way to do ? Within mailHandler, "Configurationx" is not accessible.
Thank you for your help
答案1
得分: 1
嗯,有一个有趣的猜想:只需发布一个问题,你就能自己找到解决方案。
func CreateHandler(Conf Configuration) smtpd.Handler {
// ...
// 然后返回原始的处理程序
return func(origin net.Addr, from string, to []string, data []byte) error {
log.Println("test: Foo is: " + Conf.foo) //<< ok
return nil
}
}
调用ListenAndServe:
smtpd.ListenAndServe(os.Args[1], CreateHandler(Configurationx), "MyServerApp", "")
英文:
Well, there is an interesting conjecture : just post a question and you'll find a solution yourself.
func CreateHandler ( Conf Configuration ) smtpd.Handler {
// ...
// then return the original handler
return func (origin net.Addr, from string, to []string, data []byte) error {
log.Println("test : Foo is : "+Conf.foo ) //<< ok
return nil
}
Call to ListenAndServe:
smtpd.ListenAndServe(os.Args[1], CreateHandler(Configurationx), "MyServerApp", "")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论