Documentation
¶
Overview ¶
servergroup is a library that makes starting and stopping multiple concurrent servers easy.
Example ¶
package main import ( "context" "fmt" "os" "os/signal" "golang.org/x/sys/unix" "github.com/110y/servergroup" ) // Your servers must implement servergroup.Server interface: // // type Server interface { // Start(context.Context) error // } var ( _ servergroup.Server = (*server1)(nil) _ servergroup.Server = (*server2)(nil) ) type server1 struct{} func (s *server1) Start(ctx context.Context) error { // Your own server logic here. (e.g. Call http.Server.Serve) <-ctx.Done() return nil } type server2 struct{} func (s *server2) Start(ctx context.Context) error { // Your own server logic here. (e.g. Call http.Server.Serve) <-ctx.Done() return nil } func main() { } func main() { var group servergroup.Group // Add your servers to the Group by calling Group.Add. group.Add(&server1{}) group.Add(&server2{}) ctx, cancel := signal.NotifyContext(context.Background(), unix.SIGTERM) defer cancel() // Group.Start calls Start methods of all added servers concurrently. // When the context is canceled, Group.Start waits for all servers to stop and returns an error if any of them failed. if err := group.Start(ctx); err != nil { fmt.Fprint(os.Stderr, err.Error()) os.Exit(1) } os.Exit(0) }
Output:
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
View Source
var ( ErrAlreadyStarted = errors.New("already started") ErrTerminationTimeout = errors.New("termination timeout") )
Functions ¶
This section is empty.
Types ¶
type Group ¶
type Group struct {
// contains filtered or unexported fields
}
Group represents a group of servers.
func (*Group) Add ¶
Add adds a server to the group. If the group is already started, Add do nothing.
type Option ¶
type Option interface {
// contains filtered or unexported methods
}
Option controls how Group.Start behaves.
func WithTerminationTimeout ¶
WithTerminationTimeout returns an Option that specifies the timeout duration for the termination.
type Server ¶
type Server interface { // Start starts the server and should block until the context is done. Start(context.Context) error }
Server represents a server that can be added to a Group.
type ServerFunc ¶
ServerFunc is a function that implements Server interface. It can be used to wrap a function as a Server like below:
group.Add(servergroup.ServerFunc(func(ctx context.Context) error { // do something <-ctx.Done() return nil }))
Click to show internal directories.
Click to hide internal directories.