Moving starting server part into new server.go file. Using the new serve() function from this file into main.go

This commit is contained in:
Maxime Delporte
2025-11-23 15:54:32 +01:00
parent f88edf082e
commit 78d9edf62b
2 changed files with 29 additions and 22 deletions

View File

@@ -4,13 +4,12 @@ import (
"context" "context"
"database/sql" "database/sql"
"flag" "flag"
"fmt"
"greenlight.craftr.fr/internal/data"
"log/slog" "log/slog"
"net/http"
"os" "os"
"time" "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. // 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" _ "github.com/lib/pq"
) )
@@ -104,25 +103,8 @@ func main() {
models: data.NewModels(db), models: data.NewModels(db),
} }
/* // Call app.serve() to start the server.
Declare a HTTP server which listens on the port provided in the config struct, err = app.serve()
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()
if err != nil { if err != nil {
logger.Error(err.Error()) logger.Error(err.Error())
os.Exit(1) os.Exit(1)

25
cmd/api/server.go Normal file
View File

@@ -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()
}