package exegroup import ( "context" "fmt" "net/http" "sync/atomic" ) // HttpListenAndServe 提供 [http.Server] 的启动和停止函数; func HttpListenAndServe(port int, handler http.Handler) (func(ctx context.Context) error, func(ctx context.Context)) { server := &http.Server{Addr: fmt.Sprintf(":%d", port), Handler: handler} inShutdown := &atomic.Bool{} c := make(chan error, 1) goFunc := func(_ context.Context) error { err := server.ListenAndServe() if inShutdown.Load() { err = <-c } return err } stopFunc := func(ctx context.Context) { inShutdown.Store(true) c <- server.Shutdown(ctx) } return goFunc, stopFunc }