From 3806e66cf19747f01030686bc919755bae62ae59 Mon Sep 17 00:00:00 2001 From: kevin Date: Sun, 8 Nov 2020 13:17:14 +0800 Subject: [PATCH] simplify http server starter --- rest/internal/starter.go | 38 ++++++++------------------------------ 1 file changed, 8 insertions(+), 30 deletions(-) diff --git a/rest/internal/starter.go b/rest/internal/starter.go index 660dc2b6..fba0d449 100644 --- a/rest/internal/starter.go +++ b/rest/internal/starter.go @@ -2,7 +2,6 @@ package internal import ( "context" - "crypto/tls" "fmt" "net/http" @@ -10,48 +9,27 @@ import ( ) func StartHttp(host string, port int, handler http.Handler) error { - addr := fmt.Sprintf("%s:%d", host, port) - server := buildHttpServer(addr, handler) - return start(server, func(srv *http.Server) error { + return start(host, port, handler, func(srv *http.Server) error { return srv.ListenAndServe() }) } func StartHttps(host string, port int, certFile, keyFile string, handler http.Handler) error { - addr := fmt.Sprintf("%s:%d", host, port) - server, err := buildHttpsServer(addr, handler, certFile, keyFile) - if err != nil { - return err - } - - return start(server, func(srv *http.Server) error { + return start(host, port, handler, func(srv *http.Server) error { // certFile and keyFile are set in buildHttpsServer - return srv.ListenAndServeTLS("", "") + return srv.ListenAndServeTLS(certFile, keyFile) }) } -func buildHttpServer(addr string, handler http.Handler) *http.Server { - return &http.Server{Addr: addr, Handler: handler} -} - -func buildHttpsServer(addr string, handler http.Handler, certFile, keyFile string) (*http.Server, error) { - cert, err := tls.LoadX509KeyPair(certFile, keyFile) - if err != nil { - return nil, err +func start(host string, port int, handler http.Handler, run func(srv *http.Server) error) error { + server := &http.Server{ + Addr: fmt.Sprintf("%s:%d", host, port), + Handler: handler, } - - config := tls.Config{Certificates: []tls.Certificate{cert}} - return &http.Server{ - Addr: addr, - Handler: handler, - TLSConfig: &config, - }, nil -} - -func start(server *http.Server, run func(srv *http.Server) error) error { waitForCalled := proc.AddWrapUpListener(func() { server.Shutdown(context.Background()) }) defer waitForCalled() + return run(server) }