refactor: simplify tls config in rest (#1181)
This commit is contained in:
@@ -2,38 +2,46 @@ package internal
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/tal-tech/go-zero/core/logx"
|
||||
"github.com/tal-tech/go-zero/core/proc"
|
||||
)
|
||||
|
||||
// StartOption defines the method to customize http.Server.
|
||||
type StartOption func(srv *http.Server)
|
||||
|
||||
// StartHttp starts a http server.
|
||||
func StartHttp(host string, port int, handler http.Handler) error {
|
||||
return start(host, port, handler, nil, func(srv *http.Server) error {
|
||||
func StartHttp(host string, port int, handler http.Handler, opts ...StartOption) error {
|
||||
return start(host, port, handler, func(srv *http.Server) error {
|
||||
return srv.ListenAndServe()
|
||||
})
|
||||
}, opts...)
|
||||
}
|
||||
|
||||
// StartHttps starts a https server.
|
||||
func StartHttps(host string, port int, certFile, keyFile string, tlsConfig *tls.Config, handler http.Handler) error {
|
||||
return start(host, port, handler, tlsConfig, func(srv *http.Server) error {
|
||||
func StartHttps(host string, port int, certFile, keyFile string, handler http.Handler,
|
||||
opts ...StartOption) error {
|
||||
return start(host, port, handler, func(srv *http.Server) error {
|
||||
// certFile and keyFile are set in buildHttpsServer
|
||||
return srv.ListenAndServeTLS(certFile, keyFile)
|
||||
})
|
||||
}, opts...)
|
||||
}
|
||||
|
||||
func start(host string, port int, handler http.Handler, tlsConfig *tls.Config, run func(srv *http.Server) error) (err error) {
|
||||
func start(host string, port int, handler http.Handler, run func(srv *http.Server) error,
|
||||
opts ...StartOption) (err error) {
|
||||
server := &http.Server{
|
||||
Addr: fmt.Sprintf("%s:%d", host, port),
|
||||
Handler: handler,
|
||||
}
|
||||
if tlsConfig != nil {
|
||||
server.TLSConfig = tlsConfig
|
||||
for _, opt := range opts {
|
||||
opt(server)
|
||||
}
|
||||
|
||||
waitForCalled := proc.AddWrapUpListener(func() {
|
||||
server.Shutdown(context.Background())
|
||||
if e := server.Shutdown(context.Background()); err != nil {
|
||||
logx.Error(e)
|
||||
}
|
||||
})
|
||||
defer func() {
|
||||
if err == http.ErrServerClosed {
|
||||
|
||||
Reference in New Issue
Block a user