diff options
author | Alexander Kiryukhin <alexander@kiryukhin.su> | 2018-12-05 00:48:33 +0300 |
---|---|---|
committer | Alexander Kiryukhin <alexander@kiryukhin.su> | 2018-12-05 00:48:33 +0300 |
commit | c582001e89c0b81df1b9eb1e8f1857d1c075a805 (patch) | |
tree | 1269ce0169824e967e0eccc83c257f2a2ab9f445 /example/http_server.go | |
parent | 381df5413c2be2a183945aa334ff1690a2cdfb0c (diff) |
Initial commit
Diffstat (limited to 'example/http_server.go')
-rw-r--r-- | example/http_server.go | 56 |
1 files changed, 56 insertions, 0 deletions
diff --git a/example/http_server.go b/example/http_server.go new file mode 100644 index 0000000..b1d0181 --- /dev/null +++ b/example/http_server.go @@ -0,0 +1,56 @@ +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") +} |