2020-07-29 18:00:04 +08:00
|
|
|
package internal
|
2020-07-26 17:09:05 +08:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2020-07-31 11:45:16 +08:00
|
|
|
"fmt"
|
2020-07-26 17:09:05 +08:00
|
|
|
"net/http"
|
|
|
|
|
2022-01-04 15:51:32 +08:00
|
|
|
"github.com/zeromicro/go-zero/core/logx"
|
|
|
|
"github.com/zeromicro/go-zero/core/proc"
|
2020-07-26 17:09:05 +08:00
|
|
|
)
|
|
|
|
|
2021-10-31 14:10:47 +08:00
|
|
|
// StartOption defines the method to customize http.Server.
|
2022-03-04 17:54:09 +08:00
|
|
|
type StartOption func(svr *http.Server)
|
2021-10-31 14:10:47 +08:00
|
|
|
|
2021-03-01 19:15:35 +08:00
|
|
|
// StartHttp starts a http server.
|
2021-10-31 14:10:47 +08:00
|
|
|
func StartHttp(host string, port int, handler http.Handler, opts ...StartOption) error {
|
2022-03-04 17:54:09 +08:00
|
|
|
return start(host, port, handler, func(svr *http.Server) error {
|
|
|
|
return svr.ListenAndServe()
|
2021-10-31 14:10:47 +08:00
|
|
|
}, opts...)
|
2020-07-31 11:45:16 +08:00
|
|
|
}
|
|
|
|
|
2021-03-01 19:15:35 +08:00
|
|
|
// StartHttps starts a https server.
|
2021-10-31 14:10:47 +08:00
|
|
|
func StartHttps(host string, port int, certFile, keyFile string, handler http.Handler,
|
|
|
|
opts ...StartOption) error {
|
2022-03-04 17:54:09 +08:00
|
|
|
return start(host, port, handler, func(svr *http.Server) error {
|
2020-11-08 13:08:00 +08:00
|
|
|
// certFile and keyFile are set in buildHttpsServer
|
2022-03-04 17:54:09 +08:00
|
|
|
return svr.ListenAndServeTLS(certFile, keyFile)
|
2021-10-31 14:10:47 +08:00
|
|
|
}, opts...)
|
2020-07-31 11:45:16 +08:00
|
|
|
}
|
|
|
|
|
2022-03-04 17:54:09 +08:00
|
|
|
func start(host string, port int, handler http.Handler, run func(svr *http.Server) error,
|
2021-10-31 14:10:47 +08:00
|
|
|
opts ...StartOption) (err error) {
|
2020-11-08 13:17:14 +08:00
|
|
|
server := &http.Server{
|
|
|
|
Addr: fmt.Sprintf("%s:%d", host, port),
|
|
|
|
Handler: handler,
|
2020-07-31 11:45:16 +08:00
|
|
|
}
|
2021-10-31 14:10:47 +08:00
|
|
|
for _, opt := range opts {
|
|
|
|
opt(server)
|
2021-10-31 12:56:25 +08:00
|
|
|
}
|
2021-10-31 14:10:47 +08:00
|
|
|
|
2020-11-08 13:08:00 +08:00
|
|
|
waitForCalled := proc.AddWrapUpListener(func() {
|
2022-06-29 21:35:01 +08:00
|
|
|
if e := server.Shutdown(context.Background()); e != nil {
|
2021-10-31 14:10:47 +08:00
|
|
|
logx.Error(e)
|
|
|
|
}
|
2020-11-05 11:56:40 +08:00
|
|
|
})
|
2021-07-24 12:57:56 +08:00
|
|
|
defer func() {
|
|
|
|
if err == http.ErrServerClosed {
|
|
|
|
waitForCalled()
|
|
|
|
}
|
|
|
|
}()
|
2020-11-08 13:17:14 +08:00
|
|
|
|
2020-11-08 13:08:00 +08:00
|
|
|
return run(server)
|
2020-11-05 11:56:40 +08:00
|
|
|
}
|