Home > Software engineering >  How to provide additional data to a go handler
How to provide additional data to a go handler

Time:10-22

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

CodePudding user response:

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", "")
  •  Tags:  
  • go
  • Related