Skip to content

Latest commit

 

History

History
93 lines (71 loc) · 2.3 KB

README_ZH.md

File metadata and controls

93 lines (71 loc) · 2.3 KB

lifecycle

PkgGoDev license Go Report Card codecov Build Status

English | 中文

📖 介绍

一个简单的应用生命周期管理工具,方便接入多个服务实例。

🚀 特性

  • 支持挂载多个 Server。
  • 方便应用和服务之间传递元数据。
  • 优雅地处理服务启动和终止。
  • 提供可拓展的清理函数钩子。

🧰 安装

go get -u github.com/qmdx00/lifecycle

🛠 使用

简单地实现 Server interface,并挂载到应用中即可。

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.