diff --git a/cmd/api/main.go b/cmd/api/main.go index 9169b0e..7a24e7c 100644 --- a/cmd/api/main.go +++ b/cmd/api/main.go @@ -3,6 +3,7 @@ package main import ( "context" "errors" + "flag" "fmt" "log/slog" "net/http" @@ -10,6 +11,7 @@ import ( "os/signal" "strconv" "syscall" + "time" "git.vitatech.com.cn/leo/proto.git/micro_layout/client" @@ -19,12 +21,38 @@ import ( ) func main() { + healthcheckOnly := flag.Bool("healthcheck", false, "按服务配置检查健康状态并退出") + flag.Parse() + if *healthcheckOnly { + if err := checkHealth(); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + return + } if err := run(); err != nil { slog.Error("application stopped", "error", err) os.Exit(1) } } +func checkHealth() error { + cfg, err := config.Load() + if err != nil { + return err + } + client := &http.Client{Timeout: 3 * time.Second} + response, err := client.Get(fmt.Sprintf("http://127.0.0.1:%d/health", cfg.Server.Port)) + if err != nil { + return err + } + defer response.Body.Close() + if response.StatusCode != http.StatusOK { + return fmt.Errorf("HTTP healthcheck returned status %d", response.StatusCode) + } + return nil +} + func run() error { cfg, err := config.Load() if err != nil {