Core functionality for new aiterp.net servers
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
1.5 KiB

package wrouter
import (
"net/http"
"strings"
"git.aiterp.net/gisle/wrouter/auth"
)
type Func func(http.ResponseWriter, *http.Request, *auth.User)
type IDFunc func(http.ResponseWriter, *http.Request, string, *auth.User)
type Resource struct {
list Func
create Func
get IDFunc
update IDFunc
delete IDFunc
}
func NewResource(list, create Func, get, update, delete IDFunc) *Resource {
return &Resource{list, create, get, update, delete}
}
func (resource *Resource) Handle(path string, w http.ResponseWriter, req *http.Request, user *auth.User) bool {
// Get the subpath out of the path
subpath := req.URL.Path[len(path):]
if subpath[0] == '/' {
subpath = subpath[1:]
}
// Error out on bad IDs which contains /es
if x := strings.Index(subpath, "/"); x != -1 {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(400)
w.Write([]byte("Invalid ID: " + subpath))
return true
}
// Route it to the resource
switch req.Method {
case "GET":
{
if subpath != "" {
resource.get(w, req, subpath, user)
} else {
resource.list(w, req, user)
}
}
case "POST":
{
if subpath != "" {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(400)
w.Write([]byte("ID not allowed in POST"))
return true
}
resource.create(w, req, user)
}
case "PATCH", "PUT":
{
resource.update(w, req, subpath, user)
}
case "DELETE":
{
resource.delete(w, req, subpath, user)
}
}
return true
}