From de880bf082084204f0f53de856ef69bcbfdee470 Mon Sep 17 00:00:00 2001 From: Nixon Date: Tue, 13 Aug 2024 14:03:57 -0700 Subject: [PATCH] first --- go.mod | 3 ++ keydb_extension.go | 92 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 95 insertions(+) create mode 100644 go.mod create mode 100644 keydb_extension.go diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..fd5af3e --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module sillyhats.mips.uk/pdf/caddy-keydb-codebreaker + +go 1.21.4 diff --git a/keydb_extension.go b/keydb_extension.go new file mode 100644 index 0000000..637d58c --- /dev/null +++ b/keydb_extension.go @@ -0,0 +1,92 @@ +package keydbextension + +import ( + "context" + "fmt" + "net/http" + "time" + + "github.com/caddyserver/caddy/v2" + "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" + "github.com/caddyserver/caddy/v2/modules/caddyhttp" + "github.com/go-redis/redis/v8" +) + +func init() { + caddy.RegisterModule(KeyDBHandler{}) +} + +type KeyDBHandler struct { + Address string `json:"address"` + Password string `json:"password"` + DB int `json:"db"` + client *redis.Client +} + +func (KeyDBHandler) CaddyModule() caddy.ModuleInfo { + return caddy.ModuleInfo{ + ID: "http.handlers.keydb", + New: func() caddy.Module { return new(KeyDBHandler) }, + } +} + +func (h *KeyDBHandler) Provision(ctx caddy.Context) error { + h.client = redis.NewClient(&redis.Options{ + Addr: h.Address, + Password: h.Password, + DB: h.DB, + }) + return nil +} + +func (h KeyDBHandler) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { + hash := r.URL.Query().Get("hash") + if hash == "" { + http.Error(w, "Missing hash parameter", http.StatusBadRequest) + return nil + } + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + val, err := h.client.Get(ctx, hash).Result() + if err == redis.Nil { + http.Error(w, "Cache miss", http.StatusNotFound) + return nil + } else if err != nil { + http.Error(w, "Internal server error", http.StatusInternalServerError) + return err + } + + fmt.Fprintln(w, val) + return nil +} + +func (h *KeyDBHandler) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { + for d.Next() { + for d.NextBlock(0) { + switch d.Val() { + case "address": + if !d.Args(&h.Address) { + return d.ArgErr() + } + case "password": + if !d.Args(&h.Password) { + return d.ArgErr() + } + case "db": + if !d.Args(&h.DB) { + return d.ArgErr() + } + } + } + } + return nil +} + +var ( + _ caddy.Provisioner = (*KeyDBHandler)(nil) + _ caddyhttp.MiddlewareHandler = (*KeyDBHandler)(nil) + _ caddyfile.Unmarshaler = (*KeyDBHandler)(nil) +) +