Guards
A guard is an object that is composed of an optional name and a required handler. You can add guards to your routes in order to protect them. server.Routes = []routes.Route{
{
Pattern: "GET /api/xml/data",
Handler: data.Get,
Guards: []guards.Guards{
{Name: "jsonless", Handler: func(client *clients.Client, allow func()) {
if receive.ContentType(client) == "application/json" {
return
}
allow()
}},
},
},
} Guards will block all incoming requests by default, you must call allow() to explicitly allow the request through. In this example, the route GET /api/xml/data will decline requests with content type application/json
Composition
You can compose multiple guards in order to create more advanced restrictions. var authenticate = guards.Guard{Name: "authenticate", Handler: func(client *clients.Client, allow func()) {
session := sessions.Start(receive.SessionId(client))
if session.Verified && time.Since(session.LastActivity) <= 30*time.Minute {
allow()
return
}
send.Status(client, 401)
send.Message(client, "not authenticated")
}} var authorize = guards.Guard{Name: "authorize", Handler: func(client *clients.Client, allow func()) {
session := sessions.Start(receive.SessionId(client))
if session.UserId == receive.path("user_id") {
allow()
return
}
send.Status(client, 403)
send.Message(client, "missing permissions")
}} server.Routes = []routes.Route{
{Pattern: "GET /public", Handler: public.Get},
{Pattern: "GET /dashboard", Handler: dashboard.Get, Guards: []guards.Guard{authenticate}},
{Pattern: "GET /user/{user_id}/settings", Handler: settings.Get, Guards: []guards.Guard{authenticate, authorize}},
{Pattern: "DELETE /user/{user_id}", Handler: user.Delete, Guards: []guards.Guard{authenticate, authorize}},
}