Files
gonic/server/ctrlbase/ctrl.go
2023-09-22 19:05:55 +02:00

126 lines
3.0 KiB
Go

package ctrlbase
import (
"fmt"
"log"
"net/http"
"path"
"strings"
"go.senan.xyz/gonic/db"
"go.senan.xyz/gonic/playlist"
"go.senan.xyz/gonic/scanner"
)
type statusWriter struct {
http.ResponseWriter
status int
}
func (w *statusWriter) WriteHeader(status int) {
w.status = status
w.ResponseWriter.WriteHeader(status)
}
func (w *statusWriter) Write(b []byte) (int, error) {
if w.status == 0 {
w.status = 200
}
return w.ResponseWriter.Write(b)
}
func statusToBlock(code int) string {
var bg int
switch {
case 200 <= code && code <= 299:
bg = 42 // bright green, ok
case 300 <= code && code <= 399:
bg = 46 // bright cyan, redirect
case 400 <= code && code <= 499:
bg = 43 // bright orange, client error
case 500 <= code && code <= 599:
bg = 41 // bright red, server error
default:
bg = 47 // bright white (grey)
}
return fmt.Sprintf("\u001b[%d;1m %d \u001b[0m", bg, code)
}
type Controller struct {
DB *db.DB
PlaylistStore *playlist.Store
Scanner *scanner.Scanner
ProxyPrefix string
}
// Path returns a URL path with the proxy prefix included
func (c *Controller) Path(rel string) string {
return path.Join(c.ProxyPrefix, rel)
}
func (c *Controller) BaseURL(r *http.Request) string {
protocol := "http"
if r.TLS != nil {
protocol = "https"
}
scheme := firstExisting(
protocol, // fallback
r.Header.Get("X-Forwarded-Proto"),
r.Header.Get("X-Forwarded-Scheme"),
r.URL.Scheme,
)
host := firstExisting(
"localhost:4747", // fallback
r.Header.Get("X-Forwarded-Host"),
r.Host,
)
return fmt.Sprintf("%s://%s", scheme, host)
}
func (c *Controller) WithLogging(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// this is (should be) the first middleware. pass right though it
// by calling `next` first instead of last. when it completes all
// other middlewares and the custom ResponseWriter has been written
sw := &statusWriter{ResponseWriter: w}
next.ServeHTTP(sw, r)
// sanitise password
if q := r.URL.Query(); q.Get("p") != "" {
q.Set("p", "REDACTED")
r.URL.RawQuery = q.Encode()
}
log.Printf("response %s for `%v`", statusToBlock(sw.status), r.URL)
})
}
func (c *Controller) WithCORS(next http.Handler) http.Handler {
allowMethods := strings.Join(
[]string{http.MethodPost, http.MethodGet, http.MethodOptions, http.MethodPut, http.MethodDelete},
", ",
)
allowHeaders := strings.Join(
[]string{"Accept", "Content-Type", "Content-Length", "Accept-Encoding", "X-CSRF-Token", "Authorization"},
", ",
)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", allowMethods)
w.Header().Set("Access-Control-Allow-Headers", allowHeaders)
if r.Method == http.MethodOptions {
return
}
next.ServeHTTP(w, r)
})
}
func firstExisting(or string, strings ...string) string {
for _, s := range strings {
if s != "" {
return s
}
}
return or
}