2023-12-28 16:00:04 +05:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"log/slog"
|
|
|
|
"net/http"
|
|
|
|
"os"
|
|
|
|
"os/signal"
|
|
|
|
"syscall"
|
|
|
|
|
|
|
|
"github.com/lmittmann/tint"
|
|
|
|
)
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
configFilePath := defaultConfigPath
|
|
|
|
if len(os.Args) > 1 {
|
|
|
|
configFilePath = os.Args[1]
|
|
|
|
}
|
|
|
|
|
|
|
|
config, err := LoadConfig(configFilePath)
|
|
|
|
if err != nil {
|
|
|
|
slog.Error("Failed to load config", slog.String("err", err.Error()))
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
|
|
|
|
|
|
|
logger := slog.New(tint.NewHandler(os.Stderr, &tint.Options{
|
|
|
|
Level: config.LogLevel,
|
|
|
|
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
|
|
|
|
if a.Key == slog.TimeKey && len(groups) == 0 {
|
|
|
|
return slog.Attr{}
|
|
|
|
}
|
|
|
|
return a
|
|
|
|
}}))
|
|
|
|
slog.SetDefault(logger)
|
|
|
|
|
2023-12-29 12:16:35 +05:00
|
|
|
app, err := newApp(config)
|
2023-12-28 16:00:04 +05:00
|
|
|
if err != nil {
|
2023-12-29 12:16:35 +05:00
|
|
|
slog.Error("Failed to start app", slog.String("err", err.Error()))
|
2023-12-28 16:00:04 +05:00
|
|
|
os.Exit(1)
|
|
|
|
}
|
|
|
|
|
2023-12-29 12:16:35 +05:00
|
|
|
err = app.restartTlsListener()
|
|
|
|
if err != nil {
|
|
|
|
slog.Error("Failed to start TLS listener", slog.String("err", err.Error()))
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
2023-12-28 16:00:04 +05:00
|
|
|
|
|
|
|
go func() {
|
|
|
|
slog.Debug("Starting HTTP listener", slog.String("addr", config.HttpListenAddr))
|
|
|
|
|
|
|
|
smux := http.NewServeMux()
|
|
|
|
smux.Handle(defaultAcmeChallengePath, http.StripPrefix(defaultAcmeChallengePath, http.FileServer(http.Dir(config.AcmeChallengePath))))
|
|
|
|
smux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
2023-12-29 09:42:25 +05:00
|
|
|
http.Redirect(w, r, "https://"+r.Host+r.RequestURI, http.StatusMovedPermanently)
|
2023-12-28 16:00:04 +05:00
|
|
|
})
|
|
|
|
httpServer := http.Server{Handler: smux}
|
|
|
|
httpServer.Addr = config.HttpListenAddr
|
|
|
|
err := httpServer.ListenAndServe()
|
|
|
|
if err != nil {
|
|
|
|
slog.Error("Failed to start HTTP server", slog.String("err", err.Error()))
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2023-12-29 12:16:35 +05:00
|
|
|
go func() {
|
|
|
|
c := make(chan os.Signal, 1)
|
|
|
|
signal.Notify(c, syscall.SIGUSR1)
|
|
|
|
for {
|
|
|
|
<-c
|
|
|
|
slog.Debug("TLS keys reload requested")
|
|
|
|
|
|
|
|
err := app.reloadConfig(configFilePath)
|
|
|
|
if err != nil {
|
|
|
|
slog.Error("failed to reload TLS keys", slog.String("err", err.Error()))
|
|
|
|
}
|
|
|
|
slog.Debug("Reloading TLS keys completed")
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2023-12-28 16:00:04 +05:00
|
|
|
c := make(chan os.Signal, 1)
|
|
|
|
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
|
|
|
|
<-c
|
|
|
|
slog.Debug("Interrupt signal received.")
|
|
|
|
}
|