party/cmd/api/server.go
2026-04-08 07:51:15 +02:00

68 lines
1.2 KiB
Go

package main
import (
"context"
"errors"
"fmt"
"net/http"
"time"
"log"
"os"
"os/signal"
"syscall"
)
func (app *application) serve() error {
// Declare a HTTP server using the same settings as in our main() function.
srv := &http.Server{
Addr: fmt.Sprintf(":%d", app.config.port),
Handler: app.routes(),
ErrorLog: log.New(app.logger, "", 0),
IdleTimeout: time.Minute,
ReadTimeout: 10 * time.Second,
WriteTimeout: 30 * time.Second,
}
shutdownError := make(chan error)
go func() {
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
s := <-quit
app.logger.PrintInfo("shutting down server", map[string]string{
"signal": s.String(),
})
ctx, cancel := context.WithTimeout(context.Background(), 5 * time.Second)
defer cancel()
shutdownError <- srv.Shutdown(ctx)
}()
// Likewise log a "starting server" message.
app.logger.PrintInfo("starting server", map[string]string{
"addr": srv.Addr,
"env": app.config.env,
})
err := srv.ListenAndServe()
if !errors.Is(err, http.ErrServerClosed) {
return err
}
err = <-shutdownError
if err != nil {
return err
}
app.logger.PrintInfo("stopped server", map[string]string{
"addr": srv.Addr,
})
return nil
}