simplify http server starter

master
kevin 4 years ago
parent bd430baf52
commit 3806e66cf1

@ -2,7 +2,6 @@ package internal
import ( import (
"context" "context"
"crypto/tls"
"fmt" "fmt"
"net/http" "net/http"
@ -10,48 +9,27 @@ import (
) )
func StartHttp(host string, port int, handler http.Handler) error { func StartHttp(host string, port int, handler http.Handler) error {
addr := fmt.Sprintf("%s:%d", host, port) return start(host, port, handler, func(srv *http.Server) error {
server := buildHttpServer(addr, handler)
return start(server, func(srv *http.Server) error {
return srv.ListenAndServe() return srv.ListenAndServe()
}) })
} }
func StartHttps(host string, port int, certFile, keyFile string, handler http.Handler) error { func StartHttps(host string, port int, certFile, keyFile string, handler http.Handler) error {
addr := fmt.Sprintf("%s:%d", host, port) return start(host, port, handler, func(srv *http.Server) error {
server, err := buildHttpsServer(addr, handler, certFile, keyFile)
if err != nil {
return err
}
return start(server, func(srv *http.Server) error {
// certFile and keyFile are set in buildHttpsServer // certFile and keyFile are set in buildHttpsServer
return srv.ListenAndServeTLS("", "") return srv.ListenAndServeTLS(certFile, keyFile)
}) })
} }
func buildHttpServer(addr string, handler http.Handler) *http.Server { func start(host string, port int, handler http.Handler, run func(srv *http.Server) error) error {
return &http.Server{Addr: addr, Handler: handler} server := &http.Server{
} Addr: fmt.Sprintf("%s:%d", host, port),
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
} }
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() { waitForCalled := proc.AddWrapUpListener(func() {
server.Shutdown(context.Background()) server.Shutdown(context.Background())
}) })
defer waitForCalled() defer waitForCalled()
return run(server) return run(server)
} }

Loading…
Cancel
Save