go-zero/rest/internal/starter.go

38 lines
948 B
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"
2020-08-08 16:40:10 +08:00
"github.com/tal-tech/go-zero/core/proc"
2020-07-26 17:09:05 +08:00
)
2021-03-01 19:15:35 +08:00
// StartHttp starts a http server.
2020-07-31 11:45:16 +08:00
func StartHttp(host string, port int, handler http.Handler) error {
2020-11-08 13:17:14 +08:00
return start(host, port, handler, func(srv *http.Server) error {
2020-11-08 13:08:00 +08:00
return srv.ListenAndServe()
})
2020-07-31 11:45:16 +08:00
}
2021-03-01 19:15:35 +08:00
// StartHttps starts a https server.
2020-07-31 11:45:16 +08:00
func StartHttps(host string, port int, certFile, keyFile string, handler http.Handler) error {
2020-11-08 13:17:14 +08:00
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)
2020-11-08 13:08:00 +08:00
})
2020-07-31 11:45:16 +08:00
}
2020-11-08 13:17:14 +08:00
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,
2020-07-31 11:45:16 +08:00
}
2020-11-08 13:08:00 +08:00
waitForCalled := proc.AddWrapUpListener(func() {
server.Shutdown(context.Background())
2020-11-05 11:56:40 +08:00
})
2020-11-08 13:08:00 +08:00
defer 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
}