File: handler.go

package info (click to toggle)
golang-github-alexliesenfeld-health 0.0~git20220920.973f6339-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 228 kB
  • sloc: makefile: 3
file content (122 lines) | stat: -rw-r--r-- 4,316 bytes parent folder | download
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
package health

import (
	"encoding/json"
	"fmt"
	"net/http"
)

type (
	handlerConfig struct {
		statusCodeUp   int
		statusCodeDown int
		middleware     []Middleware
		resultWriter   ResultWriter
	}

	// Middleware is factory function that allows creating new instances of
	// a MiddlewareFunc. A MiddlewareFunc is expected to forward the function
	// call to the next MiddlewareFunc (passed in parameter 'next').
	// This way, a chain of interceptors is constructed that will eventually
	// invoke of the Checker.Check function. Each interceptor must therefore
	// invoke the 'next' interceptor. If the 'next' MiddlewareFunc is not called,
	// Checker.Check will never be executed.
	Middleware func(next MiddlewareFunc) MiddlewareFunc

	// MiddlewareFunc is a middleware for a health Handler (see NewHandler).
	// Is is invoked each time an HTTP request is processed.
	MiddlewareFunc func(r *http.Request) CheckerResult

	// ResultWriter enabled a Handler (see NewHandler) to write the CheckerResult
	// to an http.ResponseWriter in a specific format. For example, the
	// JSONResultWriter writes the result in JSON format into the response body).
	ResultWriter interface {
		// Write writes a CheckerResult into a http.ResponseWriter in a format
		// that the ResultWriter supports (such as XML, JSON, etc.).
		// A ResultWriter is expected to write at least the following information into the http.ResponseWriter:
		// (1) A MIME type header (e.g., "Content-Type" : "application/json"),
		// (2) the HTTP status code that is passed in parameter statusCode (this is necessary due to ordering constraints
		// when writing into a http.ResponseWriter (see https://github.com/alexliesenfeld/health/issues/9), and
		// (3) the response body in the format that the ResultWriter supports.
		Write(result *CheckerResult, statusCode int, w http.ResponseWriter, r *http.Request) error
	}

	// JSONResultWriter writes a CheckerResult in JSON format into an
	// http.ResponseWriter. This ResultWriter is set by default.
	JSONResultWriter struct{}
)

// Write implements ResultWriter.Write.
func (rw *JSONResultWriter) Write(result *CheckerResult, statusCode int, w http.ResponseWriter, r *http.Request) error {
	jsonResp, err := json.Marshal(result)
	if err != nil {
		return fmt.Errorf("cannot marshal response: %w", err)
	}
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.WriteHeader(statusCode)
	_, err = w.Write(jsonResp)
	return err
}

// NewJSONResultWriter creates a new instance of a JSONResultWriter.
func NewJSONResultWriter() *JSONResultWriter {
	return &JSONResultWriter{}
}

// NewHandler creates a new health check http.Handler.
func NewHandler(checker Checker, options ...HandlerOption) http.HandlerFunc {
	cfg := createConfig(options)
	return func(w http.ResponseWriter, r *http.Request) {
		// Do the check (with configured middleware)
		result := withMiddleware(cfg.middleware, func(r *http.Request) CheckerResult {
			return checker.Check(r.Context())
		})(r)

		// Write HTTP response
		disableResponseCache(w)
		statusCode := mapHTTPStatusCode(result.Status, cfg.statusCodeUp, cfg.statusCodeDown)
		cfg.resultWriter.Write(&result, statusCode, w, r)
	}
}

func disableResponseCache(w http.ResponseWriter) {
	// The response must be explicitly defined as "not cacheable"
	// to avoid returning an incorrect AvailabilityStatus as a result of caching network equipment.
	// refer to https://www.ibm.com/garage/method/practices/manage/health-check-apis/
	w.Header().Set("Cache-Control", "no-cache")
	w.Header().Set("Pragma", "no-cache")
	w.Header().Set("Expires", "-1")
}

func mapHTTPStatusCode(status AvailabilityStatus, statusCodeUp int, statusCodeDown int) int {
	if status == StatusDown || status == StatusUnknown {
		return statusCodeDown
	}
	return statusCodeUp
}

func createConfig(options []HandlerOption) handlerConfig {
	cfg := handlerConfig{
		statusCodeDown: 503,
		statusCodeUp:   200,
		middleware:     []Middleware{},
	}

	for _, opt := range options {
		opt(&cfg)
	}

	if cfg.resultWriter == nil {
		cfg.resultWriter = &JSONResultWriter{}
	}

	return cfg
}

func withMiddleware(interceptors []Middleware, target MiddlewareFunc) MiddlewareFunc {
	chain := target
	for idx := len(interceptors) - 1; idx >= 0; idx-- {
		chain = interceptors[idx](chain)
	}
	return chain
}