generated from liuzhaomax/go-maxms
/
api.go
62 lines (53 loc) · 1.59 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
package api
import (
"github.com/gin-gonic/gin"
"github.com/google/wire"
"github.com/liuzhaomax/maxblog-user/internal/middleware"
"github.com/liuzhaomax/maxblog-user/src/api_user/handler"
"github.com/liuzhaomax/maxblog-user/src/router"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"net/http"
)
var APISet = wire.NewSet(wire.Struct(new(Handler), "*"), wire.Bind(new(API), new(*Handler)))
type API interface {
Register(app *gin.Engine)
}
type Handler struct {
Middleware *middleware.Middleware
HandlerUser *handler.HandlerUser
PrometheusRegistry *prometheus.Registry
}
func (h *Handler) Register(app *gin.Engine) {
// 404
app.NoRoute(h.GetNoRoute)
// consul
app.GET("/health", h.HealthHandler)
// prometheus
app.GET("/metrics", h.MetricsHandler)
// jaeger
app.Use(h.Middleware.Tracing.Trace())
// root route
root := app.Group("")
{
// interceptor
root.Use(h.Middleware.Validator.ValidateHeaders())
root.Use(h.Middleware.Auth.ValidateSignature())
// dynamic api
router.Register(root, h.HandlerUser, h.Middleware)
}
}
func (h *Handler) RegisterStaticFS(app *gin.Engine, path string) {
app.StaticFS("/"+path, http.Dir("./"+path))
}
func (h *Handler) GetNoRoute(c *gin.Context) {
c.JSON(http.StatusNotFound, gin.H{"res": "404"})
}
func (h *Handler) HealthHandler(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"health": "ok"})
}
func (h *Handler) MetricsHandler(c *gin.Context) {
promhttp.HandlerFor(h.PrometheusRegistry, promhttp.HandlerOpts{
Registry: h.PrometheusRegistry,
}).ServeHTTP(c.Writer, c.Request)
}