-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathapi.go
More file actions
101 lines (82 loc) · 2.41 KB
/
api.go
File metadata and controls
101 lines (82 loc) · 2.41 KB
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
package api
import (
"context"
"fmt"
"net/http"
"os"
"os/signal"
"syscall"
"time"
json "github.com/goccy/go-json"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/helmet"
fiberlogger "github.com/gofiber/fiber/v2/middleware/logger"
"github.com/gofiber/fiber/v2/middleware/pprof"
fiberrecover "github.com/gofiber/fiber/v2/middleware/recover"
"go.uber.org/zap"
"sigs.k8s.io/external-dns/provider"
"github.com/stackitcloud/external-dns-stackit-webhook/pkg/metrics"
)
type Api interface {
Listen(port string) error
Test(req *http.Request, msTimeout ...int) (resp *http.Response, err error)
}
type api struct {
logger *zap.Logger
app *fiber.App
}
func (a api) Test(req *http.Request, msTimeout ...int) (resp *http.Response, err error) {
return a.app.Test(req, msTimeout...)
}
func (a api) Listen(port string) error {
go func() {
err := a.app.Listen(fmt.Sprintf(":%s", port))
if err != nil {
a.logger.Fatal("Error starting the server", zap.String(logFieldError, err.Error()))
}
}()
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
sig := <-sigCh
a.logger.Info(
"shutting down server due to received signal",
zap.String("signal", sig.String()),
)
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
err := a.app.ShutdownWithContext(ctx)
if err != nil {
a.logger.Error("error shutting down server", zap.String("err", err.Error()))
}
cancel()
return err
}
//go:generate mockgen -destination=./mock/api.go -source=./api.go Provider
type Provider interface {
provider.Provider
}
func New(logger *zap.Logger, middlewareCollector metrics.HttpApiMetrics, provider provider.Provider) Api {
app := fiber.New(fiber.Config{
DisableStartupMessage: true,
JSONEncoder: json.Marshal,
JSONDecoder: json.Unmarshal,
})
registerAt(app, "/metrics")
app.Get("/healthz", Health)
app.Use(NewMetricsMiddleware(middlewareCollector))
app.Use(fiberlogger.New())
app.Use(pprof.New(pprof.Config{Prefix: "/pprof"}))
app.Use(fiberrecover.New())
app.Use(helmet.New())
webhookRoutes := webhook{
provider: provider,
logger: logger,
}
app.Get("/records", webhookRoutes.Records)
app.Get("/", webhookRoutes.GetDomainFilter)
app.Post("/records", webhookRoutes.ApplyChanges)
app.Post("/adjustendpoints", webhookRoutes.AdjustEndpoints)
return &api{
logger: logger,
app: app,
}
}