to Config struct for configging
This commit is contained in:
41
main.go
41
main.go
@@ -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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user