Last active
April 29, 2022 17:44
-
-
Save edwintye/8d4708deba94a4471cd808081b14009e to your computer and use it in GitHub Desktop.
Example main with chan args
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"github.com/gorilla/mux" | |
"github.com/oklog/run" | |
"log" | |
"net/http" | |
"os" | |
"os/signal" | |
"syscall" | |
) | |
func getServer() *http.Server { | |
r := mux.NewRouter() | |
r.HandleFunc("/some-handler", func(http.ResponseWriter, *http.Request) {}) | |
srv := &http.Server{ | |
Handler: r, | |
Addr: ":8080", | |
} | |
return srv | |
} | |
func Main(done chan bool) error { | |
g := run.Group{} | |
{ | |
srv := getServer() | |
g.Add(func() error { | |
log.Println("Service initialization - HTTP server started") | |
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed { | |
log.Println("Error in http server : " + err.Error()) | |
return err | |
} | |
log.Println("Service shutting down") | |
return nil | |
}, func(error) { | |
_ = srv.Shutdown(context.Background()) | |
}) | |
} | |
{ | |
sig := make(chan os.Signal, 1) | |
g.Add(func() error { | |
signal.Notify(sig, os.Interrupt, syscall.SIGTERM) | |
select { | |
case <-sig: | |
case <-done: | |
} | |
return nil | |
}, func(error) { | |
}) | |
} | |
return g.Run() | |
} | |
func main() { | |
if err := Main(nil); err != nil { | |
log.Printf("Service exit due to %s\n", err.Error()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment