41 lines
853 B
Go
41 lines
853 B
Go
package hookcmd
|
|||
|
|
|
||
|
|
import (
|
||
|
|
"context"
|
||
|
|
"encoding/json"
|
||
|
|
"io"
|
||
|
|
"log/slog"
|
||
|
|
"net/http"
|
||
|
|
)
|
||
|
|
|
||
|
|
const Timeout = 7 * 24 * 60 * 60
|
||
|
|
|
||
|
|
type Func func(ctx context.Context, input json.RawMessage) (map[string]any, error)
|
||
|
|
|
||
|
|
func Command(url string) string {
|
||
|
|
return "curl -sS --data-binary @- " + url
|
||
|
|
}
|
||
|
|
|
||
|
|
func Handler(hooks map[string]Func) http.HandlerFunc {
|
||
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
||
|
|
event := r.PathValue("event")
|
||
|
|
fn := hooks[event]
|
||
|
|
if fn == nil {
|
||
|
|
http.NotFound(w, r)
|
||
|
|
return
|
||
|
|
}
|
||
|
|
body, err := io.ReadAll(r.Body)
|
||
|
|
if err != nil {
|
||
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
||
|
|
return
|
||
|
|
}
|
||
|
|
out, err := fn(r.Context(), body)
|
||
|
|
if err != nil {
|
||
|
|
slog.Error("hook failed", "event", event, "err", err)
|
||
|
|
out = map[string]any{}
|
||
|
|
}
|
||
|
|
w.Header().Set("Content-Type", "application/json")
|
||
|
|
json.NewEncoder(w).Encode(out)
|
||
|
|
}
|
||
|
|
}
|