go-zero/rest/internal/starter.go

54 lines
1.3 KiB
Go
Raw Normal View History

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"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/proc"
2020-07-26 17:09:05 +08:00
)
// StartOption defines the method to customize http.Server.
type StartOption func(srv *http.Server)
2021-03-01 19:15:35 +08:00
// StartHttp starts a http server.
func StartHttp(host string, port int, handler http.Handler, opts ...StartOption) error {
return start(host, port, handler, func(srv *http.Server) error {
2020-11-08 13:08:00 +08:00
return srv.ListenAndServe()
}, opts...)
2020-07-31 11:45:16 +08:00
}
2021-03-01 19:15:35 +08:00
// StartHttps starts a https server.
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 {
2020-11-08 13:08:00 +08:00
// certFile and keyFile are set in buildHttpsServer
2020-11-08 13:17:14 +08:00
return srv.ListenAndServeTLS(certFile, keyFile)
}, opts...)
2020-07-31 11:45:16 +08:00
}
func start(host string, port int, handler http.Handler, run func(srv *http.Server) error,
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
}
for _, opt := range opts {
opt(server)
}
2020-11-08 13:08:00 +08:00
waitForCalled := proc.AddWrapUpListener(func() {
if e := server.Shutdown(context.Background()); err != nil {
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
}