blob: a8072bb51edb66a172de391f61eeb042db8612fb (
plain) (
blame)
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
|
// +build ignore
package main
import (
"context"
"io"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"github.com/neonxp/rutina"
)
func main() {
// New instance with builtin context. Alternative: r, ctx := rutina.WithContext(ctx)
r, _ := rutina.New()
srv := &http.Server{Addr: ":8080"}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "hello world\n")
})
// Starting http server and listen connections
r.Go(func(ctx context.Context) error {
if err := srv.ListenAndServe(); err != nil {
return err
}
log.Println("Server stopped")
return nil
})
// Gracefully stoping server when context canceled
r.Go(func(ctx context.Context) error {
<-ctx.Done()
log.Println("Stopping server...")
return srv.Shutdown(ctx)
})
// OS signals subscriber
r.Go(func(ctx context.Context) error {
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGTERM, syscall.SIGINT)
select {
case <-sig:
log.Println("TERM or INT signal received")
case <-ctx.Done():
}
return nil
})
if err := r.Wait(); err != nil {
log.Fatal(err)
}
log.Println("All routines successfully stopped")
}
|