pages-server/main.go
2024-04-03 18:43:08 -05:00

69 lines
1.7 KiB
Go

package main
import (
"crypto/tls"
"fmt"
"net/http"
"os"
"strconv"
"github.com/CAFxX/httpcompression"
_ "github.com/joho/godotenv/autoload"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/rs/zerolog/pkgerrors"
"git.gay/gitgay/pages/certificates"
"git.gay/gitgay/pages/handler"
"git.gay/h/certmagic"
)
var (
HTTPS_PORT, _ = strconv.Atoi(os.Getenv("HTTPS_PORT"))
HTTP_PORT, _ = strconv.Atoi(os.Getenv("PORT"))
ENABLE_HTTPS = os.Getenv("ENABLE_HTTPS") != "false"
)
func init() {
zerolog.ErrorStackMarshaler = pkgerrors.MarshalStack
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
zerolog.SetGlobalLevel(zerolog.InfoLevel)
if _, debug := os.LookupEnv("DEBUG"); debug {
zerolog.SetGlobalLevel(zerolog.DebugLevel)
}
}
func main() {
done := make(chan bool, 1)
var acmeIssuer *certmagic.ACMEIssuer
var tlsConfig *tls.Config
if ENABLE_HTTPS {
acmeIssuer, tlsConfig = certificates.GetConfig(HTTP_PORT, HTTPS_PORT)
}
compressor, _ := httpcompression.DefaultAdapter()
pagesHandler := compressor(handler.Handler())
if ENABLE_HTTPS {
go func() {
listeningHTTPSAddress := fmt.Sprintf("%s:%v", "0.0.0.0", HTTPS_PORT)
log.Info().Msgf("HTTPS server listening on %s", listeningHTTPSAddress)
err := ListenAndServe(listeningHTTPSAddress, tlsConfig, pagesHandler)
if err != nil {
log.Panic().Err(err).Msg("Couldn't start QUIC server")
}
}()
}
go func() {
listeningHTTPAddress := fmt.Sprintf("%s:%v", "0.0.0.0", HTTP_PORT)
log.Info().Msgf("HTTP server listening on %s", listeningHTTPAddress)
err := http.ListenAndServe(listeningHTTPAddress, acmeIssuer.HTTPChallengeHandler(pagesHandler))
if err != nil {
log.Panic().Err(err).Msg("Couldn't start HTTP server")
}
}()
<-done
}