English | 中文
A simple application lifecycle management tool with multiple servers.
- Easy to attach servers to application.
- Convenient to get metadata from application.
- Handle server shutdown gracefully.
- Provide hooks for cleanup function.
go get -u github.com/qmdx00/lifecycle
Just implement server interface, then attach servers to application, here is an example.
package main
import (
"context"
"github.com/qmdx00/lifecycle"
"log"
"net/http"
)
func main() {
app := lifecycle.NewApp(
lifecycle.WithName("test"),
lifecycle.WithVersion("v1.0"),
)
app.Attach("echo", NewEchoServer())
app.Cleanup(func() error {
log.Println("do cleanup")
return nil
})
if err := app.Run(); err != nil {
log.Fatal(err)
}
}
func NewEchoServer() lifecycle.Server {
handler := http.NewServeMux()
handler.HandleFunc("/echo", func(writer http.ResponseWriter, request *http.Request) {
_, _ = writer.Write([]byte("hello world"))
})
return &EchoServer{
srv: &http.Server{
Addr: ":3000",
Handler: handler,
},
}
}
type EchoServer struct {
srv *http.Server
}
func (e *EchoServer) Run(ctx context.Context) error {
info, _ := lifecycle.FromContext(ctx)
log.Printf("server %s start\n", info.Name())
return e.srv.ListenAndServe()
}
func (e *EchoServer) Stop(ctx context.Context) error {
info, _ := lifecycle.FromContext(ctx)
log.Printf("server %s stop\n", info.Name())
return e.srv.Shutdown(ctx)
}
© Wimi Yuan, 2021~time.Now
Released under the MIT License.