74 lines
1.8 KiB
Go

// Package http provides functions to handle incoming HTTP requests
package http
import (
prometheus "http-broadcaster/Prometheus"
varnish "http-broadcaster/Varnish"
"io"
"log"
"net/http"
"strconv"
"strings"
"time"
)
// logRequest print the requests and wanted informations in log file
func logRequest(t time.Time, r *http.Request, s int, h string) {
// Test if X-Cache-Tags header is empty
if h == "" {
log.Printf("%s %s - - %s \"%s %s %s\" %d 0 \"-\" \"%s\" %d\n",
r.Host,
strings.Split(r.RemoteAddr, ":")[0],
t.Format("[02/Jan/2006:15:04:05 -0700]"),
r.Method,
r.URL.Path,
r.Proto,
s,
r.UserAgent(),
time.Since(t).Milliseconds(),
)
} else {
log.Printf("%s %s - - %s \"%s %s %s\" %d 0 \"-\" \"%s\" %d %s\n",
r.Host,
strings.Split(r.RemoteAddr, ":")[0],
t.Format("[02/Jan/2006:15:04:05 -0700]"),
r.Method,
r.URL.Path,
r.Proto,
s,
r.UserAgent(),
time.Since(t).Milliseconds(),
h,
)
}
}
// RequestHandler handles requests to broadcast to all varnish instances.
func RequestHandler(w http.ResponseWriter, r *http.Request) {
// If metrics are not enabled, return 404 on /metrics path.
if r.URL.Path == "/metrics" && !prometheus.MetricsEnabled {
w.WriteHeader(404)
_, _ = io.WriteString(w, strconv.Itoa(404))
return
}
t := time.Now()
url := r.URL.String()
method := r.Method
tag := r.Header.Get("X-Cache-Tags")
status := varnish.SendToVarnish(method, url, tag)
if prometheus.MetricsEnabled {
prometheus.IncrementClientCounterVec(method)
}
// Return HTTP code 405 if not all varnish servers returned 200.
if status != 200 {
w.WriteHeader(405)
}
logRequest(t, r, status, tag)
_, _ = io.WriteString(w, strconv.Itoa(status))
}
// HealthHandler handles healthcheck requests and return 200.
func HealthHandler(w http.ResponseWriter, _ *http.Request) {
_, _ = io.WriteString(w, "OK")
}