2 ==================================================================================
3 Copyright (c) 2019 AT&T Intellectual Property.
4 Copyright (c) 2019 Nokia
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
10 http://www.apache.org/licenses/LICENSE-2.0
12 Unless required by applicable law or agreed to in writing, software
13 distributed under the License is distributed on an "AS IS" BASIS,
14 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 See the License for the specific language governing permissions and
16 limitations under the License.
17 ==================================================================================
24 "github.com/gorilla/mux"
29 ReadyURL = "/ric/v1/health/ready"
30 AliveURL = "/ric/v1/health/alive"
33 type StatusCb func() bool
40 func NewRouter() *Router {
42 router: mux.NewRouter().StrictSlash(true),
43 cbMap: make([]StatusCb, 0),
46 // Inject default routes for health probes
47 r.InjectRoute(ReadyURL, readyHandler, "GET")
48 r.InjectRoute(AliveURL, aliveHandler, "GET")
53 func (r *Router) serviceChecker(inner http.HandlerFunc) http.HandlerFunc {
54 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
55 Logger.Info("restapi: method=%s url=%s", req.Method, req.URL.RequestURI())
56 if req.URL.RequestURI() == AliveURL || r.CheckStatus() {
57 inner.ServeHTTP(w, req)
59 respondWithJSON(w, http.StatusServiceUnavailable, nil)
64 func (r *Router) InjectRoute(url string, handler http.HandlerFunc, method string) *mux.Route {
65 return r.router.HandleFunc(url, r.serviceChecker(handler)).Methods(method)
68 func (r *Router) InjectQueryRoute(url string, h http.HandlerFunc, m string, q ...string) *mux.Route {
69 return r.router.HandleFunc(url, r.serviceChecker(h)).Methods(m).Queries(q...)
72 func (r *Router) InjectStatusCb(f StatusCb) {
73 r.cbMap = append(r.cbMap, f)
76 func (r *Router) CheckStatus() (status bool) {
77 if len(r.cbMap) == 0 {
81 for _, f := range r.cbMap {
87 func readyHandler(w http.ResponseWriter, r *http.Request) {
88 respondWithJSON(w, http.StatusOK, nil)
91 func aliveHandler(w http.ResponseWriter, r *http.Request) {
92 respondWithJSON(w, http.StatusOK, nil)
95 func respondWithJSON(w http.ResponseWriter, code int, payload interface{}) {
96 w.Header().Set("Content-Type", "application/json")
99 response, _ := json.Marshal(payload)