ess-etl-go/cmd/server/main.go

111 lines
2.4 KiB
Go

package main
import (
"context"
"flag"
"log"
"net/http"
"os"
"os/signal"
"runtime/pprof"
"runtime/trace"
"syscall"
"gitea.urkob.com/urko/crono"
"gitea.urkob.com/urko/ess-etl-go/config"
apihttp "gitea.urkob.com/urko/ess-etl-go/internal/api/http"
"gitea.urkob.com/urko/ess-etl-go/internal/services"
"gitea.urkob.com/urko/ess-etl-go/pkg/adapter/repository/mongodb/employee_wi"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")
var traceflag = flag.String("trace", "", "write trace to file")
func main() {
flag.Parse()
if *cpuprofile != "" {
f, err := os.Create(*cpuprofile)
if err != nil {
log.Fatal(err)
}
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
}
// Add pprof endpoints
go func() {
if *cpuprofile != "" {
log.Println(http.ListenAndServe("localhost:6060", nil))
}
}()
if *traceflag != "" {
log.Println("trace on")
trace.Start(os.Stdout)
defer func() {
log.Println("on stop")
trace.Stop()
}()
}
cr := crono.New()
defer cr.Table()
cfg := config.NewConfig(".env")
ctx, cancel := context.WithCancel(signalContext(context.Background()))
defer cancel()
dbOpts := options.Client()
dbOpts.ApplyURI(cfg.DbAddress)
client, err := mongo.NewClient(dbOpts)
if err != nil {
log.Fatalln("mongo.NewClient", err)
}
log.Println("mongodb client is connected")
if err = client.Connect(ctx); err != nil {
log.Fatalln("client.Connect", err)
}
employeeWICollection := client.Database(cfg.DbName).Collection(cfg.WorkInformationCollection)
professionalRepo := employee_wi.NewRepo(employeeWICollection)
restServer := apihttp.
NewRestServer(cfg, cr).
WithEmployeeWIHandler(services.NewEmployeeWIService(ctx, professionalRepo)).
WithAMSHandler()
cr.MarkAndRestart("dependencies loaded")
go func() {
if err = restServer.Start(cfg.ApiPort, ""); err != nil {
log.Fatalln("restServer.Start", err)
cancel()
}
}()
<-ctx.Done()
restServer.Shutdown()
log.Println("gracefully shutdown")
}
func signalContext(ctx context.Context) context.Context {
ctx, cancel := context.WithCancel(ctx)
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
go func() {
log.Println("listening for shutdown signal")
<-sigs
log.Println("shutdown signal received")
signal.Stop(sigs)
close(sigs)
cancel()
}()
return ctx
}