rutina/example/http_server.go

47 lines
932 B
Go
Raw Normal View History

2019-01-11 17:22:06 +03:00
// +build ignore
2018-12-05 00:48:33 +03:00
package main
import (
"context"
"io"
"log"
"net/http"
2019-01-17 07:57:51 +03:00
"github.com/neonxp/rutina"
2018-12-05 00:48:33 +03:00
)
func main() {
2019-01-17 07:54:39 +03:00
// New instance with builtin context. Alternative: r, ctx := rutina.OptionContext(ctx)
2019-01-17 07:57:51 +03:00
r := rutina.New(rutina.WithStdLogger())
2018-12-05 00:48:33 +03:00
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
2019-01-17 07:54:39 +03:00
r.ListenOsSignals()
2018-12-05 00:48:33 +03:00
if err := r.Wait(); err != nil {
log.Fatal(err)
}
log.Println("All routines successfully stopped")
}