to Config struct for configging

This commit is contained in:
Bel LaPointe
2024-04-11 16:36:23 -06:00
parent 8b732b196d
commit 4c4d92478d
3 changed files with 125 additions and 7 deletions

41
main.go
View File

@@ -1,19 +1,46 @@
package main
import (
"context"
"fmt"
"net/http"
"os"
"os/signal"
"syscall"
)
func main() {
p := os.Getenv("PORT")
if p == "" {
p = "8080"
}
addr := fmt.Sprintf(":%s", p)
ctx, can := signal.NotifyContext(context.Background(), syscall.SIGINT)
defer can()
if err := http.ListenAndServe(addr, http.HandlerFunc(http.NotFound)); err != nil {
cfg, err := newConfig()
if err != nil {
panic(err)
}
if err := run(ctx, cfg); err != nil && ctx.Err() == nil {
panic(err)
}
}
func run(ctx context.Context, cfg Config) error {
select {
case <-ctx.Done():
return ctx.Err()
case err := <-listenAndServe(ctx, cfg):
return err
}
}
func listenAndServe(ctx context.Context, cfg Config) chan error {
s := http.Server{
Addr: fmt.Sprintf(":%d", cfg.Port),
}
errc := make(chan error)
go func() {
defer close(errc)
errc <- s.ListenAndServe()
}()
return errc
}