Create a role with the Go SDK
Permit.Api.Roles.Create() creates a role in the environment that your API key belongs to. This reference is for Go developers who define role-based access control (RBAC) roles from backend code. After you create a role, assign it to users with Users.AssignRole.
Roles.Create signature
func (r *Roles) Create(ctx context.Context, roleCreate models.RoleCreate) (*models.RoleRead, error)
Roles.Create parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
ctx | context.Context | Yes | The context of the request. |
roleCreate | models.RoleCreate | Yes | The role to create. Build it with models.NewRoleCreate(key, name). |
RoleCreate fields
| Field | Type | Required | Description |
|---|---|---|---|
Key | string | Yes | A URL-friendly name of the role (a slug). You use the key to refer to the role in later calls instead of the role ID (a UUID). |
Name | string | Yes | The name of the role. |
Description | *string | No | What the role represents, or which permissions it grants. Set it with SetDescription(). |
Permissions | []string | No | The permissions the role grants, each in the format <resource-key>:<action-key>, such as document:read. Set them with SetPermissions(). |
Extends | []string | No | The keys of roles that this role extends. The role inherits all the permissions of those roles. Set them with SetExtends(). |
Attributes | map[string]string | No | Key-value metadata about the role. Set it with SetAttributes(). |
Example: create a role with Roles.Create
The example uses a client named Permit, created with permit.NewPermit() as shown in Check permissions with the Go SDK, and a ctx of type context.Context.
Build the RoleCreate struct with the key role-key, the name role-name, and the read and write permissions on the resource resource-key:
roleCreate := models.NewRoleCreate("role-key", "role-name")
roleCreate.SetPermissions([]string{"resource-key:read", "resource-key:write"})
Pass the struct to Roles.Create:
role, err := Permit.Api.Roles.Create(ctx, *roleCreate)
Roles.Create return value and errors
On success, Roles.Create returns a *models.RoleRead with the role's Key, Id, Name, Description, Permissions, and Extends.
If the call fails, err holds an errors.PermitError from the github.com/permitio/permit-golang/pkg/errors package. Its StatusCode field has the HTTP status, and its ErrorCode field has one of these codes:
ErrorCode | Cause |
|---|---|
UnprocessableEntityError | HTTP 422: a field failed validation. |
Unauthorized, ForbiddenAccess | HTTP 401 or 403: the API key is invalid or has no access to the environment. |
UnexpectedError | A server error (HTTP 5xx) or a network error. |