github.com/companieshouse/lfp-pay-api@v0.0.0-20230203133422-0ca455cd79f9/main.go (about)

     1  package main
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"net/http"
     7  	"os"
     8  	"os/signal"
     9  	"syscall"
    10  	"time"
    11  
    12  	"github.com/companieshouse/chs.go/log"
    13  	"github.com/companieshouse/lfp-pay-api/config"
    14  	"github.com/companieshouse/lfp-pay-api/dao"
    15  	"github.com/companieshouse/lfp-pay-api/handlers"
    16  	"github.com/gorilla/mux"
    17  )
    18  
    19  func main() {
    20  	namespace := "lfp-pay-api"
    21  	log.Namespace = namespace
    22  
    23  	cfg, err := config.Get()
    24  	if err != nil {
    25  		log.Error(fmt.Errorf("error configuring service: %s. Exiting", err), nil)
    26  		return
    27  	}
    28  
    29  	// Create router
    30  	mainRouter := mux.NewRouter()
    31  	svc := dao.NewDAOService(cfg)
    32  
    33  	handlers.Register(mainRouter, cfg, svc)
    34  
    35  	log.Info("Starting " + namespace)
    36  
    37  	h := &http.Server{
    38  		Addr:    cfg.BindAddr,
    39  		Handler: mainRouter,
    40  	}
    41  
    42  	stop := make(chan os.Signal, 1)
    43  	signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
    44  
    45  	// run server in new go routine to allow app shutdown signal wait below
    46  	go func() {
    47  		log.Info("starting server...", log.Data{"port": cfg.BindAddr})
    48  		err = h.ListenAndServe()
    49  		log.Info("server stopping...")
    50  		if err != nil && err != http.ErrServerClosed {
    51  			log.Error(err)
    52  			svc.Shutdown()
    53  			os.Exit(1)
    54  		}
    55  	}()
    56  
    57  	// wait for app shutdown message before attempting to close server gracefully
    58  	<-stop
    59  
    60  	log.Info("shutting down server...")
    61  	svc.Shutdown()
    62  	timeout := time.Duration(5) * time.Second
    63  	ctx, cancel := context.WithTimeout(context.Background(), timeout)
    64  	defer cancel()
    65  
    66  	err = h.Shutdown(ctx)
    67  	if err != nil {
    68  		log.Error(fmt.Errorf("failed to shutdown server gracefully: [%v]", err))
    69  	} else {
    70  		log.Info("server shutdown gracefully")
    71  	}
    72  }