package exegroup import ( "context" "net" "net/http" "strconv" "sync/atomic" "time" ) // HTTPListenAndServe 提供 [http.Server] 的启动和停止函数; func HTTPListenAndServe(port int, handler http.Handler) (func(ctx context.Context) error, func(ctx context.Context)) { server := &http.Server{ Addr: net.JoinHostPort("", strconv.Itoa(port)), Handler: handler, ReadHeaderTimeout: time.Second, } 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 }