diff options
author | Grail Finder <wohilas@gmail.com> | 2025-03-29 11:12:53 +0300 |
---|---|---|
committer | Grail Finder <wohilas@gmail.com> | 2025-03-29 11:12:53 +0300 |
commit | 3921db6166e2da895257496bb76dd115556699d3 (patch) | |
tree | 1be4f739121761085f69cb7706c60dbbe98a93e9 /internal/server |
init
Diffstat (limited to 'internal/server')
-rw-r--r-- | internal/server/main.go | 59 | ||||
-rw-r--r-- | internal/server/router.go | 31 |
2 files changed, 90 insertions, 0 deletions
diff --git a/internal/server/main.go b/internal/server/main.go new file mode 100644 index 0000000..2c3c8d6 --- /dev/null +++ b/internal/server/main.go @@ -0,0 +1,59 @@ +package server + +import ( + "demoon/config" + "demoon/internal/database/repos" + "demoon/internal/handlers" + + "context" + "log/slog" + "os" + "os/signal" + "syscall" +) + +// Server interface +type Server interface { + Listen() +} + +type server struct { + config config.Config + actions *handlers.Handlers + ctx context.Context + close context.CancelFunc +} + +func (srv *server) stopOnSignal(close context.CancelFunc) { + // listen for termination signals + sigc := make(chan os.Signal, 1) + signal.Notify(sigc, os.Interrupt, syscall.SIGINT) + signal.Notify(sigc, os.Interrupt, syscall.SIGTERM) + sig := <-sigc + + log := slog.New(slog.NewJSONHandler(os.Stdout, nil)) + log.Info("Shutting down services", + "section", "server", + "app_event", "terminate", + "signal", sig.String()) + close() + os.Exit(0) +} + +func NewServer(cfg config.Config, log *slog.Logger, repo repos.FullRepo) Server { + ctx, close := context.WithCancel(context.Background()) + actions := handlers.NewHandlers(cfg, log, repo) + return &server{ + config: cfg, + actions: actions, + ctx: ctx, + close: close, + } +} + +// Listen for new events that affect the market and process them +func (srv *server) Listen() { + // start the http server + go srv.ListenToRequests() + srv.stopOnSignal(srv.close) +} diff --git a/internal/server/router.go b/internal/server/router.go new file mode 100644 index 0000000..989766c --- /dev/null +++ b/internal/server/router.go @@ -0,0 +1,31 @@ +package server + +import ( + "fmt" + "net/http" + "time" +) + +func (srv *server) ListenToRequests() { + h := srv.actions + mux := http.NewServeMux() + server := &http.Server{ + Addr: fmt.Sprintf("localhost:%s", srv.config.ServerConfig.Port), + Handler: h.GetSession(mux), + ReadTimeout: time.Second * 5, + WriteTimeout: time.Second * 5, + } + + fs := http.FileServer(http.Dir("assets/")) + mux.Handle("GET /assets/", http.StripPrefix("/assets/", fs)) + + mux.HandleFunc("GET /ping", h.Ping) + mux.HandleFunc("GET /", h.MainPage) + mux.HandleFunc("POST /login", h.HandleLogin) + mux.HandleFunc("POST /signup", h.HandleSignup) + + // ====== elements ====== + + fmt.Println("Listening", "addr", server.Addr) + server.ListenAndServe() +} |