How to keep live server command with channel

143 Views Asked by At

I am using gorilla/mux for the serving my go app. And for the keeping live that http server I am using a channel like that in my server command like in below.

        
&cobra.Command{
        Use:   "server",
        Run: func(cmd *cobra.Command, args []string) {
        
            _, _, serverErr := runServer()
            if serverErr != nil {
                panic(err)
            }

            // keep the command up and running until it gets terminated
            c := make(chan os.Signal, 2)
            signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
            <-c
}

Inside the runServer:

    p := conf.Server.Port
    listener, err := net.Listen("tcp", ":"+p)
    if err != nil {
        return nil, nil, errors.Wrap(err, "Unable to start server")
    }

    server := &http.Server{Handler: srv}

    go func() {
        if err := server.Serve(listener); err != nil {
            fmt.Println(err)
        }
    }()

    logger.Infof("Service available at port %s", p)

    return server, listener, nil

And I am trying to implement air for the autowatch my changes and recompile again and run server command.

Problem is when air re-run the server command, server gives port already using error because of the channel is still live. Is there any way to kill that signal from cmd and run again or another way to kill the port and run again?

0

There are 0 best solutions below