go: Integrating a more custom server with unit

Ingo Krabbe ikrabbe.ask at gmail.com
Fri Dec 29 08:45:26 UTC 2017


Good Morning group,

I would like to try a little go web application with the unitd. The problem is, that I

a) use custom TCP input (not http)
b) and therefore I have unified the approach to open the http port(s) too.

Actually I wrote a bit of code, that might also help you with your unit code,
but what I want to know from you is, how I can add the port to unit, without using unit.ListenAndServe.

http.ListenAndServe I use l := net.Listen and then http.Serve(l):

===CODE START
func (srv *Server) start() {
         for i := range httpaddr {
                 f := srv.runhttpserver(uint(i))
                 go f()
         }

         for i := range netaddr {
                 f := srv.runnetserver(uint(i))
                 go f()
         }
}

func (srv *Server) runhttpserver(i uint) func() {
         srv.wg.Add(1)
         return func() {
                 l, err := net.Listen("tcp", httpaddr[i])

                 if err != nil {
                         srv.s[i] = nil
                         srv.errchan <- err
                 } else {
                         srv.wg.Add(1)
                         srv.s[i] = &http.Server{}
                         srv.log.Printf("HTTP %d Listen %s", i, httpaddr[i])
                         srv.errchan <- srv.s[i].Serve(l)
                         srv.log.Printf("finished HTTP Listen %s", httpaddr[i])
                         srv.wg.Done()
                 }
                 srv.wg.Done()
         }
}

func (srv *Server) runnetserver(i uint) func() {
         srv.wg.Add(1)
         return func() {
                 l, err := net.Listen("tcp", netaddr[i])

                 if err != nil {
                         srv.l[i] = nil
                         srv.errchan <- err
                 } else {
                         srv.wg.Add(1)
                         srv.log.Printf("NET %d Listen %s", i, netaddr[i])
                         srv.l[i] = l
                         /* blocking code goes here */
                         srv.errchan <- l.Close()
                         srv.log.Printf("finished NET Listen %s", netaddr[i])
                         srv.wg.Done()
                 }
                 srv.wg.Done()
         }
}
===CODE END

So having port sets httpaddr[] and netaddr[] I add all connections to a wait group and drop the application
when all waitgroups are done.

It should be quite simple to add the unit connection here too, but on first sight I don't understand your code. Maybe you have a hint.

Best Regards,

Ingo



More information about the unit mailing list