You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
crate/exegroup/httpserver.go

28 lines
651 B
Go

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
}