-
Notifications
You must be signed in to change notification settings - Fork 36
/
server_impl.go
57 lines (48 loc) · 1.5 KB
/
server_impl.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
package httpserver
import (
"context"
"encoding/hex"
"errors"
"log/slog"
"net/http"
)
var _ Server = (*serverImpl)(nil)
// New creates a new Server with the given publicKey eventHandlerFunc and ConfigOpt(s)
func New(publicKey string, eventHandlerFunc EventHandlerFunc, opts ...ConfigOpt) Server {
config := DefaultConfig()
config.Apply(opts)
config.Logger = config.Logger.With(slog.String("name", "httpserver"))
hexDecodedKey, err := hex.DecodeString(publicKey)
if err != nil {
config.Logger.Debug("error while decoding hex string", slog.String("err", err.Error()))
}
return &serverImpl{
config: *config,
publicKey: hexDecodedKey,
eventHandlerFunc: eventHandlerFunc,
}
}
type serverImpl struct {
config Config
publicKey PublicKey
eventHandlerFunc EventHandlerFunc
}
func (s *serverImpl) Start() {
s.config.ServeMux.Handle(s.config.URL, HandleInteraction(s.publicKey, s.config.Logger, s.eventHandlerFunc))
s.config.HTTPServer.Addr = s.config.Address
s.config.HTTPServer.Handler = s.config.ServeMux
go func() {
var err error
if s.config.CertFile != "" && s.config.KeyFile != "" {
err = s.config.HTTPServer.ListenAndServeTLS(s.config.CertFile, s.config.KeyFile)
} else {
err = s.config.HTTPServer.ListenAndServe()
}
if !errors.Is(err, http.ErrServerClosed) {
s.config.Logger.Error("error while running http server", slog.String("err", err.Error()))
}
}()
}
func (s *serverImpl) Close(ctx context.Context) {
_ = s.config.HTTPServer.Shutdown(ctx)
}