main.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "time"
  7. "github.com/vladimirok5959/golang-ctrlc/ctrlc"
  8. )
  9. func main() {
  10. MyAppFunc := func(ctx context.Context, shutdown context.CancelFunc) *[]ctrlc.Iface {
  11. // Some custom logic
  12. // With goroutine inside
  13. test := Run()
  14. // err1 := fmt.Errorf("Startup error 1")
  15. // err2 := fmt.Errorf("Startup error 2")
  16. // return ctrlc.MakeError(shutdown, ctrlc.AppError(err1), ctrlc.AppError(err2))
  17. // Http web server
  18. mux := http.NewServeMux()
  19. mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  20. fmt.Printf("New web request (%s)!\n", r.URL.Path)
  21. // Do something hard inside (12 seconds)
  22. for i := 0; i < 12000; i++ {
  23. select {
  24. case <-ctx.Done():
  25. // Interrupt request by server
  26. fmt.Printf("[BY SERVER] OK, I will cancel (%s)!\n", r.URL.Path)
  27. return
  28. case <-r.Context().Done():
  29. // Interrupt request by client
  30. fmt.Printf("[BY CLIENT] OK, I will cancel (%s)!\n", r.URL.Path)
  31. return
  32. default:
  33. // Main some logic
  34. // Some very long logic, just for example
  35. time.Sleep(1 * time.Millisecond)
  36. }
  37. }
  38. fmt.Printf("After 12 seconds!\n")
  39. w.Header().Set("Content-Type", "text/html")
  40. if _, err := w.Write([]byte(`<div>After 12 seconds!</div>`)); err != nil {
  41. fmt.Printf("%s\n", err.Error())
  42. return
  43. }
  44. if _, err := w.Write([]byte(`<div>` + r.URL.Path + `</div>`)); err != nil {
  45. fmt.Printf("%s\n", err.Error())
  46. return
  47. }
  48. })
  49. srv := &http.Server{Addr: "127.0.0.1:8080", Handler: mux}
  50. go func() {
  51. fmt.Printf("Starting web server: http://127.0.0.1:8080/\n")
  52. if err := srv.ListenAndServe(); err != nil {
  53. if err != http.ErrServerClosed {
  54. fmt.Printf("Web server startup error: %s\n", err.Error())
  55. // Application can't working without http web server
  56. // Call cancel context func on error
  57. shutdown()
  58. return
  59. }
  60. }
  61. }()
  62. return &[]ctrlc.Iface{test, srv}
  63. }
  64. // Run application
  65. ctrlc.App(MyAppFunc)
  66. }