-
Notifications
You must be signed in to change notification settings - Fork 17
/
prober.go
63 lines (55 loc) · 1.49 KB
/
prober.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
/*
Copyright 2022 Chainguard, Inc.
SPDX-License-Identifier: Apache-2.0
*/
package prober
import (
"context"
"fmt"
"log"
"net/http"
"os"
"time"
)
// Interface is implemented by Chainguard probers to encapsulate their
// probing logic
type Interface interface {
// Probe performs a single probe and is passed the HTTP request context.
Probe(context.Context) error
}
// Func is a convenience wrapper for turning a function into an Interface.
type Func func(context.Context) error
// Probe implements Interface
func (pf Func) Probe(ctx context.Context) error {
return pf(ctx)
}
// Go launches the prober process, and does not return.
// On errors it terminates the process.
func Go(_ context.Context, i Interface) {
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
authz := os.Getenv("AUTHORIZATION")
if authz == "" {
log.Fatal("Expected AUTHORIZATION environment variable to be configured.")
}
http.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if auth := r.Header.Get("Authorization"); auth != authz {
log.Print("ERROR: request was not authorized")
http.Error(w, "not authorized", http.StatusUnauthorized)
return
}
if err := i.Probe(r.Context()); err != nil {
log.Printf("ERROR: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}))
srv := &http.Server{
Addr: fmt.Sprintf(":%s", port),
ReadHeaderTimeout: 10 * time.Second,
}
log.Fatal(srv.ListenAndServe())
}