This repository has been archived by the owner on Aug 3, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
handlers.go
181 lines (160 loc) · 4.37 KB
/
handlers.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
// Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package goscaffold
import (
"encoding/json"
"errors"
"net/http"
"net/http/pprof"
)
/*
requestHandler handles all requests and stops them if we are marked down.
*/
type requestHandler struct {
s *HTTPScaffold
child http.Handler
}
func (h *requestHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
startErr := h.s.tracker.start()
if startErr == nil {
h.child.ServeHTTP(resp, req)
h.s.tracker.end()
} else {
writeUnavailable(resp, req, NotReady, startErr)
}
}
/*
managementHandler adds support for health checks and diagnostics.
*/
type managementHandler struct {
s *HTTPScaffold
mux *http.ServeMux
child http.Handler
}
func (h *managementHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
handler, pattern := h.mux.Handler(req)
if pattern == "" && h.child != nil {
// Fall through for stuff that's not a management call
h.child.ServeHTTP(resp, req)
} else {
// Handler may be one of ours, or a built-in not found handler
handler.ServeHTTP(resp, req)
}
}
func (s *HTTPScaffold) createManagementHandler() *managementHandler {
h := &managementHandler{
s: s,
mux: http.NewServeMux(),
}
// Manually register paths from "pprof" package because we are
// not using a standard HTTP handler here.
h.mux.HandleFunc("/debug/pprof/", pprof.Index)
h.mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
h.mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
h.mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
h.mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
if s.healthPath != "" {
h.mux.HandleFunc(s.healthPath, s.handleHealth)
}
if s.readyPath != "" {
h.mux.HandleFunc(s.readyPath, s.handleReady)
}
if s.markdownPath != "" {
h.mux.HandleFunc(s.markdownPath, s.handleMarkdown)
}
return h
}
func (s *HTTPScaffold) callHealthCheck() (HealthStatus, error) {
if s.healthCheck == nil {
return OK, nil
}
status, err := s.healthCheck()
if status == OK {
return OK, nil
}
if err == nil {
return status, errors.New(status.String())
}
return status, err
}
/*
handleHealth only fails if the user's health check function tells us.
*/
func (s *HTTPScaffold) handleHealth(resp http.ResponseWriter, req *http.Request) {
if req.Method != "GET" {
resp.WriteHeader(http.StatusMethodNotAllowed)
return
}
status, healthErr := s.callHealthCheck()
if status == Failed {
writeUnavailable(resp, req, status, healthErr)
} else {
resp.WriteHeader(http.StatusOK)
}
}
/*
handleReady fails if we are marked down and also if the user's health function
tells us.
*/
func (s *HTTPScaffold) handleReady(resp http.ResponseWriter, req *http.Request) {
if req.Method != "GET" {
resp.WriteHeader(http.StatusMethodNotAllowed)
return
}
status, healthErr := s.callHealthCheck()
if status == OK {
healthErr = s.tracker.markedDown()
if healthErr != nil {
status = NotReady
}
}
if status == OK {
resp.WriteHeader(http.StatusOK)
} else {
writeUnavailable(resp, req, status, healthErr)
}
}
/*
handleMarkdown handles a request to mark down the server.
*/
func (s *HTTPScaffold) handleMarkdown(resp http.ResponseWriter, req *http.Request) {
if req.Method != s.markdownMethod {
resp.WriteHeader(http.StatusMethodNotAllowed)
return
}
req.Body.Close()
s.tracker.markDown()
if s.markdownHandler != nil {
s.markdownHandler()
}
}
func writeUnavailable(
resp http.ResponseWriter, req *http.Request,
stat HealthStatus, err error) {
mt := SelectMediaType(req, []string{"text/plain", "application/json"})
resp.WriteHeader(http.StatusServiceUnavailable)
switch mt {
case "application/json":
re := map[string]string{
"status": stat.String(),
"reason": err.Error(),
}
buf, _ := json.Marshal(&re)
resp.Header().Set("Content-Type", mt)
resp.Write(buf)
default:
resp.Header().Set("Content-Type", "text/plain")
resp.Write([]byte(err.Error()))
}
}