un http Server async and return error via channel

This commit is contained in:
Balakrishnan Balasubramanian 2023-09-11 20:28:04 -04:00
parent ee28a78eda
commit 5c43a1a4fc

View File

@ -14,12 +14,17 @@ import (
"syscall" "syscall"
) )
// AddressType of the address passed
type AddressType string type AddressType string
var ( var (
// UnixSocket - address is a unix socket, e.g. unix//run/foo.sock
UnixSocket AddressType = "UnixSocket" UnixSocket AddressType = "UnixSocket"
// SystemdFD - address is a systemd fd, e.g. sysd/fdname/myapp.socket
SystemdFD AddressType = "SystemdFD" SystemdFD AddressType = "SystemdFD"
// TCP - address is a TCP address, e.g. :1234
TCP AddressType = "TCP" TCP AddressType = "TCP"
// Unknown - address is not recognized
Unknown AddressType = "Unknown" Unknown AddressType = "Unknown"
) )
@ -231,22 +236,30 @@ func GetListener(addr string) (AddressType, net.Listener, error) {
return TCP, l, err return TCP, l, err
} }
func ListenAndServeHTTP(addr string, h http.Handler) (AddressType, *http.Server, error) { // Serve creates and serve a http server.
func Serve(addr string, h http.Handler) (AddressType, *http.Server, <-chan error, error) {
addrType, listener, err := GetListener(addr) addrType, listener, err := GetListener(addr)
if err != nil { if err != nil {
return addrType, nil, err return addrType, nil, nil, err
} }
srv := &http.Server{Handler: h} srv := &http.Server{Handler: h}
err = srv.Serve(listener) done := make(chan error)
return addrType, srv, err go func() {
done <- srv.Serve(listener)
close(done)
}()
return addrType, srv, done, nil
} }
// ListenAndServe is the drop-in replacement for `http.ListenAndServe`. // ListenAndServe is the drop-in replacement for `http.ListenAndServe`.
// Supports unix and systemd sockets in addition // Supports unix and systemd sockets in addition
func ListenAndServe(addr string, h http.Handler) error { func ListenAndServe(addr string, h http.Handler) error {
_, _, err := ListenAndServeHTTP(addr, h) _, _, done, err := Serve(addr, h)
if err != nil {
return err return err
} }
return <-done
}
// UnsetSystemdListenVars unsets the LISTEN* environment variables so they are not passed to any child processes // UnsetSystemdListenVars unsets the LISTEN* environment variables so they are not passed to any child processes
func UnsetSystemdListenVars() { func UnsetSystemdListenVars() {