-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
75 lines (66 loc) · 1.95 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
package main
import (
"context"
"fmt"
"net/http"
"time"
"github.com/vladimirok5959/golang-ctrlc/ctrlc"
)
func main() {
MyAppFunc := func(ctx context.Context, shutdown context.CancelFunc) *[]ctrlc.Iface {
// Some custom logic
// With goroutine inside
test := Run()
// err1 := fmt.Errorf("Startup error 1")
// err2 := fmt.Errorf("Startup error 2")
// return ctrlc.MakeError(shutdown, ctrlc.AppError(err1), ctrlc.AppError(err2))
// Http web server
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Printf("New web request (%s)!\n", r.URL.Path)
// Do something hard inside (12 seconds)
for i := 0; i < 12000; i++ {
select {
case <-ctx.Done():
// Interrupt request by server
fmt.Printf("[BY SERVER] OK, I will cancel (%s)!\n", r.URL.Path)
return
case <-r.Context().Done():
// Interrupt request by client
fmt.Printf("[BY CLIENT] OK, I will cancel (%s)!\n", r.URL.Path)
return
default:
// Main some logic
// Some very long logic, just for example
time.Sleep(1 * time.Millisecond)
}
}
fmt.Printf("After 12 seconds!\n")
w.Header().Set("Content-Type", "text/html")
if _, err := w.Write([]byte(`<div>After 12 seconds!</div>`)); err != nil {
fmt.Printf("%s\n", err.Error())
return
}
if _, err := w.Write([]byte(`<div>` + r.URL.Path + `</div>`)); err != nil {
fmt.Printf("%s\n", err.Error())
return
}
})
srv := &http.Server{Addr: "127.0.0.1:8080", Handler: mux}
go func() {
fmt.Printf("Starting web server: http://127.0.0.1:8080/\n")
if err := srv.ListenAndServe(); err != nil {
if err != http.ErrServerClosed {
fmt.Printf("Web server startup error: %s\n", err.Error())
// Application can't working without http web server
// Call cancel context func on error
shutdown()
return
}
}
}()
return &[]ctrlc.Iface{test, srv}
}
// Run application
ctrlc.App(MyAppFunc)
}