2020-02-03 07:21:07 +01:00
|
|
|
package serv
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
)
|
|
|
|
|
|
|
|
type actionFn func(w http.ResponseWriter, r *http.Request) error
|
|
|
|
|
2020-04-11 08:45:06 +02:00
|
|
|
func newAction(a *Action) (http.Handler, error) {
|
2020-02-03 07:21:07 +01:00
|
|
|
var fn actionFn
|
|
|
|
var err error
|
|
|
|
|
|
|
|
if len(a.SQL) != 0 {
|
|
|
|
fn, err = newSQLAction(a)
|
|
|
|
} else {
|
|
|
|
return nil, fmt.Errorf("invalid config for action '%s'", a.Name)
|
|
|
|
}
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
httpFn := func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
if err := fn(w, r); err != nil {
|
2020-04-10 08:27:43 +02:00
|
|
|
renderErr(w, err, nil)
|
2020-02-03 07:21:07 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return http.HandlerFunc(httpFn), nil
|
|
|
|
}
|
|
|
|
|
2020-04-11 08:45:06 +02:00
|
|
|
func newSQLAction(a *Action) (actionFn, error) {
|
2020-02-03 07:21:07 +01:00
|
|
|
fn := func(w http.ResponseWriter, r *http.Request) error {
|
2020-04-10 08:27:43 +02:00
|
|
|
_, err := db.ExecContext(r.Context(), a.SQL)
|
2020-02-03 07:21:07 +01:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return fn, nil
|
|
|
|
}
|