This repository has been archived by the owner on Nov 30, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
server.go
111 lines (90 loc) · 2.48 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
// Package server provides a server implementation to connect network transport
// protocols and service business logic by defining server endpoints.
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/azure-operator/v5/server/endpoint"
"github.com/giantswarm/azure-operator/v5/service"
)
type Config struct {
Logger micrologger.Logger
Service *service.Service
Viper *viper.Viper
ProjectName string
}
func New(config Config) (microserver.Server, error) {
var err error
if config.Logger == nil {
return nil, microerror.Maskf(invalidConfigError, "%T.Logger must not be empty", config)
}
if config.Service == nil {
return nil, microerror.Maskf(invalidConfigError, "%T.Service must not be empty", config)
}
if config.Viper == nil {
return nil, microerror.Maskf(invalidConfigError, "%T.Viper must not be empty", config)
}
if config.ProjectName == "" {
return nil, microerror.Maskf(invalidConfigError, "%T.ProjectName must not be empty", config)
}
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)
}
}
newServer := &server{
logger: config.Logger,
bootOnce: sync.Once{},
config: microserver.Config{
Logger: config.Logger,
ServiceName: config.ProjectName,
Viper: config.Viper,
Endpoints: []microserver.Endpoint{
endpointCollection.Healthz,
endpointCollection.Version,
},
ErrorEncoder: encodeError,
},
shutdownOnce: sync.Once{},
}
return newServer, nil
}
type server struct {
logger micrologger.Logger
bootOnce sync.Once
config microserver.Config
shutdownOnce sync.Once
}
func (s *server) Boot() {
s.bootOnce.Do(func() {
// Here goes your custom boot logic for your server/endpoint if
// any.
})
}
func (s *server) Config() microserver.Config {
return s.config
}
func (s *server) Shutdown() {
s.shutdownOnce.Do(func() {
// Here goes your custom shutdown logic for your
// server/endpoint if any.
})
}
func encodeError(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)
}