-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
53 lines (41 loc) · 971 Bytes
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package main
import (
"context"
"errors"
"fmt"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"htmxx/middleware"
)
const (
defaultShutdownPeriod = 30 * time.Second
)
func (app *application) serveHTTP() error {
srv := &http.Server{
Addr: fmt.Sprintf(":%s", app.config.httpPort),
Handler: middleware.Logging(middleware.GetUser(app.routes())),
}
shutdownErrorChan := make(chan error)
go func() {
quitChan := make(chan os.Signal, 1)
signal.Notify(quitChan, syscall.SIGINT, syscall.SIGTERM)
<-quitChan
ctx, cancel := context.WithTimeout(context.Background(), defaultShutdownPeriod)
defer cancel()
shutdownErrorChan <- srv.Shutdown(ctx)
}()
fmt.Println("starting server", "server", "addr", srv.Addr)
err := srv.ListenAndServe()
if !errors.Is(err, http.ErrServerClosed) {
return err
}
err = <-shutdownErrorChan
if err != nil {
return err
}
fmt.Println("stopped server", "server", "addr", srv.Addr)
return nil
}