-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
95 lines (78 loc) · 2.02 KB
/
server.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package server
import (
"context"
"net/http"
"sync"
"github.com/giantswarm/microerror"
microserver "github.com/giantswarm/microkit/server"
"github.com/giantswarm/micrologger"
"github.com/spf13/viper"
"github.com/giantswarm/release-operator/v3/pkg/project"
"github.com/giantswarm/release-operator/v3/server/endpoint"
"github.com/giantswarm/release-operator/v3/service"
)
// Config represents the configuration used to construct server object.
type Config struct {
Logger micrologger.Logger
Service *service.Service
Viper *viper.Viper
}
type Server struct {
// Dependencies.
logger micrologger.Logger
// Internals.
bootOnce sync.Once
config microserver.Config
shutdownOnce sync.Once
}
// New creates a new configured server object.
func New(config Config) (*Server, error) {
var err error
var endpointCollection *endpoint.Endpoint
{
c := endpoint.Config{
Logger: config.Logger,
Service: config.Service,
}
endpointCollection, err = endpoint.New(c)
if err != nil {
return nil, microerror.Mask(err)
}
}
s := &Server{
logger: config.Logger,
bootOnce: sync.Once{},
config: microserver.Config{
Logger: config.Logger,
ServiceName: project.Name(),
Viper: config.Viper,
Endpoints: []microserver.Endpoint{
endpointCollection.Healthz,
endpointCollection.Version,
},
ErrorEncoder: errorEncoder,
},
shutdownOnce: sync.Once{},
}
return s, nil
}
func (s *Server) Boot() {
s.bootOnce.Do(func() {
// Insert here custom boot logic for server/endpoint/middleware if needed.
})
}
func (s *Server) Config() microserver.Config {
return s.config
}
func (s *Server) Shutdown() {
s.shutdownOnce.Do(func() {
// Insert here custom shutdown logic for server/endpoint/middleware if needed.
})
}
func errorEncoder(ctx context.Context, err error, w http.ResponseWriter) {
rErr := err.(microserver.ResponseError)
uErr := rErr.Underlying()
rErr.SetCode(microserver.CodeInternalError)
rErr.SetMessage(uErr.Error())
w.WriteHeader(http.StatusInternalServerError)
}