forked from mono0x/my-scraper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
76 lines (66 loc) · 1.36 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
64
65
66
67
68
69
70
71
72
73
74
75
76
package main
import (
"context"
"fmt"
"log"
"net"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/joho/godotenv"
"github.com/lestrrat-go/server-starter/listener"
"github.com/mono0x/my-scraper/server"
"golang.org/x/sync/errgroup"
)
func run() error {
listeners, err := listener.ListenAll()
if err != nil && err != listener.ErrNoListeningTarget {
return fmt.Errorf("%w", err)
}
var l net.Listener
if len(listeners) > 0 {
l = listeners[0]
} else {
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
l, err = net.Listen("tcp", ":"+port)
if err != nil {
return fmt.Errorf("%w", err)
}
}
handler, err := server.NewHandler()
if err != nil {
return err
}
s := http.Server{Handler: handler}
eg := errgroup.Group{}
eg.Go(func() error {
if err := s.Serve(l); err != nil && err != http.ErrServerClosed {
return fmt.Errorf("%w", err)
}
return nil
})
eg.Go(func() error {
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, syscall.SIGTERM, os.Interrupt)
<-signalChan
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := s.Shutdown(ctx); err != nil {
return fmt.Errorf("%w", err)
}
return nil
})
return eg.Wait()
}
func main() {
log.SetFlags(log.Lshortfile)
_ = godotenv.Load()
if err := run(); err != nil {
log.Fatalf("%v\n", err)
}
}