From 78d9edf62bab804d1c2642556c9d92e08aeb5fc5 Mon Sep 17 00:00:00 2001 From: Maxime Delporte Date: Sun, 23 Nov 2025 15:54:32 +0100 Subject: [PATCH] Moving starting server part into new server.go file. Using the new serve() function from this file into main.go --- cmd/api/main.go | 26 ++++---------------------- cmd/api/server.go | 25 +++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 22 deletions(-) create mode 100644 cmd/api/server.go diff --git a/cmd/api/main.go b/cmd/api/main.go index 94974f1..c57a426 100644 --- a/cmd/api/main.go +++ b/cmd/api/main.go @@ -4,13 +4,12 @@ import ( "context" "database/sql" "flag" - "fmt" - "greenlight.craftr.fr/internal/data" "log/slog" - "net/http" "os" "time" + "greenlight.craftr.fr/internal/data" + // Import the pq driver so that it can register itself with the database/sql package. Note that we alias this import to the blank identifier, to stop the Go compiler complaining that the package isn't being used. _ "github.com/lib/pq" ) @@ -104,25 +103,8 @@ func main() { models: data.NewModels(db), } - /* - Declare a HTTP server which listens on the port provided in the config struct, - uses the servemux we created above as the handler, has some sensible timeout - settings and writes any log messages to the structured logger at Error level. - */ - srv := &http.Server{ - Addr: fmt.Sprintf(":%d", cfg.port), - Handler: app.routes(), - IdleTimeout: time.Minute, - ReadTimeout: 5 * time.Second, - WriteTimeout: 10 * time.Second, - ErrorLog: slog.NewLogLogger(logger.Handler(), slog.LevelError), - } - - // Start the HTTP server. - logger.Info("starting server", "addr", srv.Addr, "env", cfg.env) - - // Because the err variable is now already declared in the code above, we need to user = operator here, instead of the := operator. - err = srv.ListenAndServe() + // Call app.serve() to start the server. + err = app.serve() if err != nil { logger.Error(err.Error()) os.Exit(1) diff --git a/cmd/api/server.go b/cmd/api/server.go new file mode 100644 index 0000000..9508c9e --- /dev/null +++ b/cmd/api/server.go @@ -0,0 +1,25 @@ +package main + +import ( + "fmt" + "log/slog" + "net/http" + "time" +) + +func (app *application) serve() error { + // Declare a HTTP server which listens on the port provided in the config struct, uses the servemux we created above as the handler, has some sensible timeout settings and writes any log messages to the structured logger at Error level. + srv := &http.Server{ + Addr: fmt.Sprintf(":%d", app.config.port), + Handler: app.routes(), + IdleTimeout: time.Minute, + ReadTimeout: 5 * time.Second, + WriteTimeout: 10 * time.Second, + ErrorLog: slog.NewLogLogger(app.logger.Handler(), slog.LevelError), + } + + // Start the HTTP server. + app.logger.Info("starting server", "addr", srv.Addr, "env", app.config.env) + + return srv.ListenAndServe() +}