1
0
mirror of https://github.com/oauth2-proxy/oauth2-proxy.git synced 2025-01-26 05:27:28 +02:00
oauth2-proxy/pkg/middleware/healthcheck.go

53 lines
1.2 KiB
Go
Raw Normal View History

2020-06-14 16:42:05 +01:00
package middleware
import (
"fmt"
"net/http"
"github.com/justinas/alice"
)
func NewHealthCheck(paths, userAgents []string) alice.Constructor {
return func(next http.Handler) http.Handler {
return healthCheck(paths, userAgents, next)
}
}
func healthCheck(paths, userAgents []string, next http.Handler) http.Handler {
// Use a map as a set to check health check paths
pathSet := make(map[string]struct{})
for _, path := range paths {
if len(path) > 0 {
pathSet[path] = struct{}{}
}
2020-06-14 16:42:05 +01:00
}
// Use a map as a set to check health check paths
userAgentSet := make(map[string]struct{})
for _, userAgent := range userAgents {
if len(userAgent) > 0 {
userAgentSet[userAgent] = struct{}{}
}
2020-06-14 16:42:05 +01:00
}
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
if isHealthCheckRequest(pathSet, userAgentSet, req) {
rw.WriteHeader(http.StatusOK)
fmt.Fprintf(rw, "OK")
return
}
next.ServeHTTP(rw, req)
})
}
func isHealthCheckRequest(paths, userAgents map[string]struct{}, req *http.Request) bool {
if _, ok := paths[req.URL.EscapedPath()]; ok {
return true
}
if _, ok := userAgents[req.Header.Get("User-Agent")]; ok {
return true
}
return false
}