-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
95 lines (84 loc) · 2.07 KB
/
handler.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
package api
import (
"encoding/json"
"fmt"
"github.com/dp1140a/geoip/models"
"github.com/dp1140a/geoip/version"
"github.com/go-chi/chi"
log "github.com/sirupsen/logrus"
"net/http"
)
type BaseHandler struct {
models.Handler
mux *chi.Mux
}
func NewBaseHandler(logger *log.Logger, m *chi.Mux) models.HandlerIFace {
bh := BaseHandler{
mux: m,
Handler: models.Handler{
Prefix: "/",
},
}
bh.Routes = []models.Route{
{
Name: "ping",
Method: http.MethodGet,
Pattern: "/ping",
HandlerFunc: bh.pingHandler,
},
{
Name: "api",
Method: http.MethodGet,
Pattern: "/api",
HandlerFunc: bh.getAPI,
},
{
Name: "version",
Method: http.MethodGet,
Pattern: "/version",
HandlerFunc: bh.getVersion,
},
}
return bh
}
func (bh BaseHandler) GetRoutes() []models.Route {
return bh.Routes
}
func (bh BaseHandler) GetService() models.Service {
return bh.Service
}
func (bh BaseHandler) GetPrefix() string {
return bh.Prefix
}
/**
GET /ping (200) -- Returns "OK"
*/
func (bh *BaseHandler) pingHandler(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("x-powered-by", "bacon")
w.Header().Set("Content-Type", "text/plain; charset=UTF-8")
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK\n"))
}
/**
GET /api (200) -- Returns JSON of API
*/
func (bh *BaseHandler) getAPI(w http.ResponseWriter, _ *http.Request) {
var routes []string
chi.Walk(bh.mux, func(method string, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error {
routes = append(routes, fmt.Sprintf("%s %s", method, route))
return nil
})
w.Header().Set("x-powered-by", "bacon")
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(routes)
}
/**
GET /version (200) -- Returns JSON of the current version
*/
func (bh *BaseHandler) getVersion(w http.ResponseWriter, _ *http.Request) {
versionInfo := version.NewVersionInfo()
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(versionInfo)
}