Skip to content

Simple application lifecycle manangement

License

Notifications You must be signed in to change notification settings

qmdx00/lifecycle

Repository files navigation

lifecycle

PkgGoDev license Go Report Card codecov Build Status

English | 中文

📖 Introduction

A simple application lifecycle management tool with multiple servers.

🚀 Features

  • Easy to attach servers to application.
  • Convenient to get metadata from application.
  • Handle server shutdown gracefully.
  • Provide hooks for cleanup function.

🧰 How to install

go get -u github.com/qmdx00/lifecycle

🛠 How to use

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)
}

📄 License

© Wimi Yuan, 2021~time.Now
Released under the MIT License.