Skip to content

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 "GET /api/xml/data" route will decline requests with content type "application/json".

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}},
}

In this example "GET /dashboard" is protected by "authenticate", while "GET /user/{user_id}/settings" and "DELETE /user/{user_id}" are protected by both "authenticate" and "authorize".