github.com/lingyao2333/mo-zero@v1.4.1/rest/internal/starter.go (about)

     1  package internal
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"net"
     7  	"net/http"
     8  
     9  	"github.com/lingyao2333/mo-zero/core/logx"
    10  	"github.com/lingyao2333/mo-zero/core/proc"
    11  )
    12  
    13  // StartOption defines the method to customize http.Server.
    14  type StartOption func(svr *http.Server)
    15  
    16  // StartHttp starts a http server.
    17  func StartHttp(host string, port int, handler http.Handler, opts ...StartOption) error {
    18  	return start(host, port, handler, func(svr *http.Server) error {
    19  		//return svr.ListenAndServe()
    20  
    21  		l, err := net.Listen("tcp4", fmt.Sprintf("%s:%d", host, port))
    22  		if err != nil {
    23  			panic("failed to listen:" + err.Error())
    24  		}
    25  		return svr.Serve(l)
    26  	}, opts...)
    27  }
    28  
    29  // StartHttps starts a https server.
    30  func StartHttps(host string, port int, certFile, keyFile string, handler http.Handler,
    31  	opts ...StartOption) error {
    32  	return start(host, port, handler, func(svr *http.Server) error {
    33  		// certFile and keyFile are set in buildHttpsServer
    34  		return svr.ListenAndServeTLS(certFile, keyFile)
    35  	}, opts...)
    36  }
    37  
    38  func start(host string, port int, handler http.Handler, run func(svr *http.Server) error,
    39  	opts ...StartOption) (err error) {
    40  	server := &http.Server{
    41  		Addr:    fmt.Sprintf("%s:%d", host, port),
    42  		Handler: handler,
    43  	}
    44  	for _, opt := range opts {
    45  		opt(server)
    46  	}
    47  
    48  	waitForCalled := proc.AddWrapUpListener(func() {
    49  		if e := server.Shutdown(context.Background()); e != nil {
    50  			logx.Error(e)
    51  		}
    52  	})
    53  	defer func() {
    54  		if err == http.ErrServerClosed {
    55  			waitForCalled()
    56  		}
    57  	}()
    58  
    59  	return run(server)
    60  }