go-zero/rest/internal/starter.go

58 lines
1.4 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
"crypto/tls"
"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
)
2020-07-31 11:45:16 +08:00
func StartHttp(host string, port int, handler http.Handler) error {
addr := fmt.Sprintf("%s:%d", host, port)
server := buildHttpServer(addr, handler)
2020-11-08 13:08:00 +08:00
return start(server, func(srv *http.Server) error {
return srv.ListenAndServe()
})
2020-07-31 11:45:16 +08:00
}
func StartHttps(host string, port int, certFile, keyFile string, handler http.Handler) error {
addr := fmt.Sprintf("%s:%d", host, port)
2020-11-08 13:08:00 +08:00
server, err := buildHttpsServer(addr, handler, certFile, keyFile)
if err != nil {
2020-07-31 11:45:16 +08:00
return err
}
2020-11-08 13:08:00 +08:00
return start(server, func(srv *http.Server) error {
// certFile and keyFile are set in buildHttpsServer
return srv.ListenAndServeTLS("", "")
})
2020-07-31 11:45:16 +08:00
}
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
}
config := tls.Config{Certificates: []tls.Certificate{cert}}
return &http.Server{
Addr: addr,
Handler: handler,
TLSConfig: &config,
}, nil
}
2020-11-05 11:56:40 +08:00
2020-11-08 13:08:00 +08:00
func start(server *http.Server, run func(srv *http.Server) error) error {
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()
return run(server)
2020-11-05 11:56:40 +08:00
}