-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathmain.go
63 lines (54 loc) · 1.42 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
package main
import (
"context"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"github.com/kelseyhightower/envconfig"
"github.com/rs/zerolog"
"golang.org/x/sync/errgroup"
)
type Settings struct {
BaseDomain string `envconfig:"BASE_DOMAIN" required:"true"`
Port string `envconfig:"PORT" default:"45070"`
}
var (
s Settings
log = zerolog.New(os.Stderr).Output(zerolog.ConsoleWriter{Out: os.Stdout}).With().Timestamp().Logger()
)
func main() {
// load environment variables
err := envconfig.Process("", &s)
if err != nil {
log.Fatal().Err(err).Msg("couldn't process envconfig")
return
}
// setup handlers
mux := http.NewServeMux()
mux.HandleFunc("/ask", handleCaddyAsk)
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
subdomain, found := strings.CutSuffix(r.Host, "."+s.BaseDomain)
if found {
handleSubdomain(subdomain, w, r)
} else if r.Host == s.BaseDomain {
handleHome(w, r)
} else {
handleMagicCNAME(w, r)
}
})
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer cancel()
server := &http.Server{Addr: ":" + s.Port, Handler: mux}
log.Info().Msg("running on http://localhost:" + s.Port)
g, ctx := errgroup.WithContext(ctx)
g.Go(server.ListenAndServe)
g.Go(func() error {
<-ctx.Done()
return server.Shutdown(context.Background())
})
if err := g.Wait(); err != nil {
log.Debug().Err(err).Msg("exit reason")
}
}