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.

93 lines
1.9 KiB

package wrouter
import (
"net/http"
"strings"
"git.aiterp.net/gisle/wrouter/response"
"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
PrivateRead bool
PrivateWrite bool
}
func NewResource(list, create Func, get, update, delete IDFunc) *Resource {
return &Resource{list, create, get, update, delete, false, false}
}
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 len(subpath) > 0 && subpath[0] == '/' {
subpath = subpath[1:]
}
// Error out on bad IDs which contains /es
if x := strings.Index(subpath, "/"); x != -1 {
response.Text(w, 400, "Invalid ID: "+subpath)
return true
}
// Route it to the resource
switch req.Method {
case "GET":
{
if resource.PrivateRead && user == nil {
response.Text(w, 401, "Not logged in")
return true
}
if subpath != "" {
resource.get(w, req, subpath, user)
} else {
resource.list(w, req, user)
}
}
case "POST":
{
if resource.PrivateWrite && user == nil {
response.Text(w, 401, "Not logged in")
return true
}
if subpath != "" {
response.Text(w, 400, "ID not allowed in POST")
return true
}
resource.create(w, req, user)
}
case "PATCH", "PUT":
{
if resource.PrivateWrite && user == nil {
response.Text(w, 401, "Not logged in")
return true
}
resource.update(w, req, subpath, user)
}
case "DELETE":
{
if resource.PrivateWrite && user == nil {
response.Text(w, 401, "Not logged in")
return true
}
resource.delete(w, req, subpath, user)
}
}
return true
}