-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
99 lines (93 loc) · 2.55 KB
/
main.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package main
import (
"context"
"crypto/sha256"
"embed"
"encoding/hex"
"fmt"
"io"
"log/slog"
"net"
"net/http"
"os"
"os/signal"
"sync"
"time"
"github.com/kodehat/portkey/internal/build"
"github.com/kodehat/portkey/internal/config"
"github.com/kodehat/portkey/internal/metrics"
"github.com/kodehat/portkey/internal/server"
)
//go:embed static
var static embed.FS
func main() {
ctx := context.Background()
build.LoadBuildDetails(getCssResourceHash())
config.Load()
metrics.Load()
if err := run(ctx, config.C, os.Stdin, os.Stdout, os.Stderr); err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err)
os.Exit(1)
}
}
func run(ctx context.Context, config config.Config, stdin io.Reader, stdout, stderr io.Writer) error {
ctx, cancel := signal.NotifyContext(ctx, os.Interrupt)
defer cancel()
logger := slog.New(config.GetLogHandler(stdout))
slog.SetDefault(logger)
srv := server.NewServer(
logger,
&config,
static,
)
httpServer := &http.Server{
Addr: net.JoinHostPort(config.Host, config.Port),
Handler: srv,
}
go func() {
logger.Info("server is now accepting connections", "address", httpServer.Addr)
if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
fmt.Fprintf(os.Stderr, "error listening and serving: %s\n", err)
}
}()
var metricHttpServer *http.Server
if config.EnableMetrics {
metricsSrv := server.NewMetricsServer(logger)
metricHttpServer = &http.Server{
Addr: net.JoinHostPort(config.MetricsHost, config.MetricsPort),
Handler: metricsSrv,
}
go func() {
logger.Info("metrics server is now accepting connections", "address", metricHttpServer.Addr)
if err := metricHttpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
fmt.Fprintf(os.Stderr, "error listening and serving: %s\n", err)
}
}()
}
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
<-ctx.Done()
// make a new context for the Shutdown (thanks Alessandro Rosetti)
shutdownCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
if err := httpServer.Shutdown(shutdownCtx); err != nil {
fmt.Fprintf(os.Stderr, "error shutting down http server: %s\n", err)
}
if metricHttpServer != nil {
if err := metricHttpServer.Shutdown(shutdownCtx); err != nil {
fmt.Fprintf(os.Stderr, "error shutting down metrics server: %s\n", err)
}
}
}()
wg.Wait()
return nil
}
func getCssResourceHash() string {
cssFile, _ := static.ReadFile("static/css/main.css")
hasher := sha256.New()
hasher.Write(cssFile)
sha := hex.EncodeToString(hasher.Sum(nil))
return sha[:8]
}