-
Notifications
You must be signed in to change notification settings - Fork 0
/
starter.go
65 lines (52 loc) · 1.42 KB
/
starter.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
@Date: 2021/11/10 17:01
@Author: yvanz
@File : starter
*/
package apiserver
import (
"context"
"fmt"
"net/http"
"github.com/yvanz/gin-tmpl/pkg/logger"
)
// StartOption defines the method to customize http.Server.
type StartOption func(srv *http.Server)
// StartHTTP starts a http server.
func StartHTTP(host string, port int, handler http.Handler, opts ...StartOption) error {
listenAddr := fmt.Sprintf("%s:%d", host, port)
return start(listenAddr, handler, func(srv *http.Server) error {
return srv.ListenAndServe()
}, opts...)
}
// StartHTTPS starts a https server.
func StartHTTPS(conf APIConfig, handler http.Handler, opts ...StartOption) error {
listenAddr := fmt.Sprintf("%s:%d", conf.App.HostIP, conf.App.APIPort)
return start(listenAddr, handler, func(srv *http.Server) error {
return srv.ListenAndServeTLS(conf.App.CertFile, conf.App.KeyFile)
}, opts...)
}
func start(listenAddr string, handler http.Handler, run func(*http.Server) error, opts ...StartOption) (err error) {
server := &http.Server{
Addr: listenAddr,
Handler: handler,
}
for _, opt := range opts {
opt(server)
}
waitForCalled := AddWrapUpListener(func() {
if e := server.Shutdown(context.Background()); e != nil {
logger.Error(e)
}
})
defer func() {
if err != nil {
if err == http.ErrServerClosed {
waitForCalled()
} else {
logger.Errorf("http with an error: %s", err.Error())
}
}
}()
return run(server)
}