-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
executable file
·293 lines (268 loc) · 8.21 KB
/
api.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
// Package api implements setup and functions for the Fiber API
// via the https://docs.gofiber.io/ package.
//
// Note: API functions are not documented here, see this API endpoint for Swagger docs and enpoint testing:
//
// /api/v1/docs/
package api
import (
"fmt"
"log"
"time"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/logger"
"github.com/gofiber/fiber/v2/middleware/monitor"
"github.com/mwiater/golangdocker/common"
"github.com/mwiater/golangdocker/config"
"github.com/mwiater/golangdocker/sysinfo"
"github.com/shirou/gopsutil/v3/host"
fiberSwagger "github.com/swaggo/fiber-swagger"
_ "github.com/mwiater/golangdocker/docs"
)
// apiFalseRoot ... Redirect root of API server to "/api/v1"
// @Summary Redirect root of API server to "/api/v1"
// @Description Redirect root of API server to "/api/v1"
// @Tags API Routes Root
// @Accept */*
// @Produce json
// @Success 200 {object} []string
// @Router / [get]
func apiFalseRoot(c *fiber.Ctx) error {
err := c.Redirect("/api/v1")
if err != nil {
return fiber.NewError(fiber.StatusServiceUnavailable, err.Error())
}
return nil
}
// readAPIIndex ... Get all API routes
// @Summary Get all API routes
// @Description Get all API routes
// @Tags API Routes
// @Accept */*
// @Produce json
// @Success 200 {object} map[string]interface{}
// @Router /api/v1 [get]
func readAPIIndex(c *fiber.Ctx) error {
apiRoutes, err := sysinfo.GetAPIRoutes(c)
if err != nil {
return fiber.NewError(fiber.StatusServiceUnavailable, err.Error())
}
c.Status(200).JSON(&fiber.Map{"apiRoutes": apiRoutes}) //nolint
return nil
}
func apiSwaggerDocs(c *fiber.Ctx) error {
err := c.Redirect("/api/v1/docs/index.html")
if err != nil {
return fiber.NewError(fiber.StatusServiceUnavailable, err.Error())
}
return nil
}
// readMemInfo ... Get system memory info
// @Summary Get system memory info
// @Description Get system memory info
// @Tags System Memory
// @Accept */*
// @Produce json
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/resource/memory [get]
func readMemInfo(c *fiber.Ctx) error {
debug := false
if c.Locals("debug") == true {
debug = true
}
memInfo, err := sysinfo.GetMemInfo(debug)
if err != nil {
return fiber.NewError(fiber.StatusServiceUnavailable, err.Error())
}
c.Status(200).JSON(&fiber.Map{"memInfo": memInfo}) //nolint
return nil
}
// readCPUInfo ... Get system cpu info
// @Summary Get system cpu info
// @Description Get system cpu info
// @Tags System CPU
// @Accept */*
// @Produce json
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/resource/cpu [get]
func readCPUInfo(c *fiber.Ctx) error {
debug := false
if c.Locals("debug") == true {
debug = true
}
cpuInfo, err := sysinfo.GetCPUInfo(debug)
if err != nil {
return fiber.NewError(fiber.StatusServiceUnavailable, err.Error())
}
c.Status(200).JSON(&fiber.Map{"cpuInfo": cpuInfo}) //nolint
return nil
}
// readHostInfo ... Get system host info
// @Summary Get system host info
// @Description Get system host info
// @Tags System Host
// @Accept */*
// @Produce json
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/resource/host [get]
func readHostInfo(c *fiber.Ctx) error {
debug := false
if c.Locals("debug") == true {
debug = true
}
hostInfo, err := sysinfo.GetHostInfo(debug)
if err != nil {
return fiber.NewError(fiber.StatusServiceUnavailable, err.Error())
}
c.Status(200).JSON(&fiber.Map{"hostInfo": hostInfo}) //nolint
return nil
}
// readNetInfo ... Get system network info
// @Summary Get system network info
// @Description Get system network info
// @Tags System Network
// @Accept */*
// @Produce json
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/resource/network [get]
func readNetInfo(c *fiber.Ctx) error {
debug := false
if c.Locals("debug") == true {
debug = true
}
netInfo, err := sysinfo.GetNetInfo(debug)
if err != nil {
return fiber.NewError(fiber.StatusServiceUnavailable, err.Error())
}
c.Status(200).JSON(&fiber.Map{"netInfo": netInfo}) //nolint
return nil
}
// readLoadInfo ... Get system load info
// @Summary Get system load info
// @Description Get system load info
// @Tags System Load
// @Accept */*
// @Produce json
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/resource/load [get]
func readLoadInfo(c *fiber.Ctx) error {
debug := false
if c.Locals("debug") == true {
debug = true
}
loadInfo, err := sysinfo.GetLoadInfo(debug)
if err != nil {
return fiber.NewError(fiber.StatusServiceUnavailable, err.Error())
}
c.Status(200).JSON(&fiber.Map{"loadInfo": loadInfo}) //nolint
return nil
}
// readAllResourceInfo ...
// @Summary Get all system info in a single call
// @Description Get all system info in a single call
// @Tags System Resources
// @Accept */*
// @Produce json
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/resource [get]
// @Router /api/v1/resource/all [get]
func readAllResourceInfo(c *fiber.Ctx) error {
debug := false
if c.Locals("debug") == true {
debug = true
}
memInfo, err := sysinfo.GetMemInfo(debug)
if err != nil {
return fiber.NewError(fiber.StatusServiceUnavailable, err.Error())
}
cpuInfo, err := sysinfo.GetCPUInfo(debug)
if err != nil {
return fiber.NewError(fiber.StatusServiceUnavailable, err.Error())
}
hostInfo, err := sysinfo.GetHostInfo(debug)
if err != nil {
return fiber.NewError(fiber.StatusServiceUnavailable, err.Error())
}
netInfo, err := sysinfo.GetNetInfo(debug)
if err != nil {
return fiber.NewError(fiber.StatusServiceUnavailable, err.Error())
}
loadInfo, err := sysinfo.GetLoadInfo(debug)
if err != nil {
return fiber.NewError(fiber.StatusServiceUnavailable, err.Error())
}
c.Status(200).JSON(&fiber.Map{"memInfo": memInfo, "cpuInfo": cpuInfo, "hostInfo": hostInfo, "netInfo": netInfo, "loadInfo": loadInfo}) //nolint
return nil
}
// routeTimerHandler creates a new middleware handler that wraps all other middleware. This is implemented so that middleware timing is caputed and set as a "Server-timing" response header.
func routeTimerHandler() fiber.Handler {
return func(c *fiber.Ctx) error {
start := time.Now()
err := c.Next()
if err != nil {
return fiber.NewError(fiber.StatusServiceUnavailable, err.Error())
}
defer func() {
c.Append("Server-timing", fmt.Sprintf("route;dur=%v", time.Since(start).Milliseconds()))
}()
return nil
}
}
// customHeaders adds middleware to include custom headers to all responses
func customHeaders(c *fiber.Ctx) error {
hostInfo, _ := host.Info()
c.Append("Hostname", fmt.Sprintf("%v", hostInfo.Hostname))
c.Append("Hostid", fmt.Sprintf("%v", hostInfo.HostID))
return c.Next()
}
// SetupApi creates Fiber API routes and middleware
//
// Returns: *fiber.App
func SetupApi() *fiber.App {
cfg, err := config.AppConfig()
if err != nil {
log.Fatal("Error: config.AppConfig()")
}
if cfg["DEBUG"] == "true" {
fmt.Println(common.ConsoleInfo("Multi-stage image build tests:"))
sysinfo.TestTZ()
sysinfo.TestTLS()
fmt.Println("")
}
app := *fiber.New()
app.Use(routeTimerHandler())
app.Use(customHeaders)
app.Use(func(c *fiber.Ctx) error {
c.Locals("port", cfg["SERVERPORT"])
c.Locals("debug", cfg["DEBUG"])
return c.Next()
})
app.Use(logger.New(logger.Config{
Format: "[${time}] ${method}:${path}: ${status} (${latency}) | Bytes In: ${bytesReceived} Bytes Out: ${bytesSent}\n",
TimeFormat: "2006-01-02T15:04:05",
TimeZone: "America/Los_Angeles",
}))
// Metrics plugin
app.Get("/api/v1/metrics", monitor.New(monitor.Config{Title: "golangdocker Metrics Page"}))
// Redirect to next route
app.Get("/", apiFalseRoot)
// List of endpoints
app.Get("/api/v1", readAPIIndex)
// Routes for Swagger API Docs
app.Get("/api/v1/index.html", apiSwaggerDocs)
app.Get("/api/v1/docs", apiSwaggerDocs)
app.Get("/api/v1/docs/*", fiberSwagger.WrapHandler)
// SysInfo Routes
// Redirect to next route
app.Get("/", apiFalseRoot)
// List of endpoints
app.Get("/api/v1", readAPIIndex)
app.Get("/api/v1/resource/memory", readMemInfo)
app.Get("/api/v1/resource/cpu", readCPUInfo)
app.Get("/api/v1/resource/host", readHostInfo)
app.Get("/api/v1/resource/network", readNetInfo)
app.Get("/api/v1/resource/load", readLoadInfo)
app.Get("/api/v1/resource/all", readAllResourceInfo)
app.Get("/api/v1/resource/", readAllResourceInfo)
return &app
}