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

34 lines
751 B
Go

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
}