-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.go
More file actions
66 lines (55 loc) · 1.88 KB
/
main.go
File metadata and controls
66 lines (55 loc) · 1.88 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
package main
import (
"context"
"errors"
"io"
"log/slog"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/1995parham-teaching/go-lecture/httpserver/handler"
)
func main() {
// Demonstrate slog.NewMultiHandler (new in Go 1.26): fan-out logs to
// stderr (text) and an in-memory JSON sink at the same time. In a real
// service the second handler would write to a file or shipper.
textHandler := slog.NewTextHandler(os.Stderr, nil)
jsonHandler := slog.NewJSONHandler(io.Discard, &slog.HandlerOptions{Level: slog.LevelInfo})
logger := slog.New(slog.NewMultiHandler(textHandler, jsonHandler))
h := handler.Hello{
From: "Golang",
Logger: logger.With("handler", "hello"),
}
mux := http.NewServeMux()
mux.HandleFunc("GET /hello", h.Get)
mux.HandleFunc("POST /hello", h.Post)
mux.HandleFunc("GET /hello/{username}", h.User)
srv := &http.Server{
Addr: "0.0.0.0:1373",
Handler: mux,
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 15 * time.Second,
WriteTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
}
// signal.NotifyContext in Go 1.26 returns a CancelCauseFunc and the
// context's cancel cause carries the received signal — useful when you
// want to log *why* you're shutting down.
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
go func() {
logger.Info("http server listening", "addr", srv.Addr)
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
logger.Error("http server failed", "error", err.Error())
}
}()
<-ctx.Done()
logger.Info("shutdown requested", "cause", context.Cause(ctx))
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
logger.Error("graceful shutdown failed", "error", err.Error())
}
}