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:
@@ -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)
|
||||
|
||||
25
cmd/api/server.go
Normal file
25
cmd/api/server.go
Normal 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()
|
||||
}
|
||||
Reference in New Issue
Block a user