You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
50 lines
1.4 KiB
50 lines
1.4 KiB
package internal |
|
|
|
import ( |
|
"context" |
|
"fmt" |
|
"git.diulo.com/mogfee/kit/core/proc" |
|
"git.diulo.com/mogfee/kit/internal/health" |
|
"git.diulo.com/mogfee/kit/logx" |
|
"net/http" |
|
) |
|
|
|
const probeNamePrefix = "rest" |
|
|
|
type StartOption func(svr *http.Server) |
|
|
|
func StartHttp(host string, port int, handler http.Handler, opts ...StartOption) error { |
|
return start(host, port, handler, func(svr *http.Server) error { |
|
return svr.ListenAndServe() |
|
}, opts...) |
|
} |
|
func StartHttps(host string, port int, certFile, keyFile string, handler http.Handler, opts ...StartOption) error { |
|
return start(host, port, handler, func(svr *http.Server) error { |
|
return svr.ListenAndServeTLS(certFile, keyFile) |
|
}, opts...) |
|
} |
|
|
|
func start(host string, port int, handler http.Handler, run func(svr *http.Server) error, opts ...StartOption) (err error) { |
|
server := &http.Server{ |
|
Addr: fmt.Sprintf("%s:%d", host, port), |
|
Handler: handler, |
|
} |
|
for _, opt := range opts { |
|
opt(server) |
|
} |
|
healthManager := health.NewHealthManager(fmt.Sprintf("%s-%s:%d", probeNamePrefix, host, port)) |
|
waitForCalled := proc.AddWrapUpListener(func() { |
|
healthManager.MarkNotReady() |
|
if e := server.Shutdown(context.Background()); e != nil { |
|
logx.Error(err) |
|
} |
|
}) |
|
defer func() { |
|
if err == http.ErrServerClosed { |
|
waitForCalled() |
|
} |
|
}() |
|
healthManager.MarkReady() |
|
health.AddProbe(healthManager) |
|
return run(server) |
|
}
|
|
|