How to Implement RBAC (Role-Based Access Control) in Go

Implement RBAC in Go by manually mapping roles to permissions and checking them in your middleware or handlers.

Go has no built-in RBAC library; you must implement it by defining roles, permissions, and a middleware that checks the current user's role against required permissions.

type Role int
const ( Admin Role = iota; User )

var permissions = map[Role][]string{Admin: {"read", "write"}, User: {"read"}}

func CheckRole(r Role, action string) bool {
 for _, p := range permissions[r] { if p == action { return true } }
 return false
}

// Usage in handler
if !CheckRole(user.Role, "write") { http.Error(w, "Forbidden", 403); return }