github.com/pyroscope-io/pyroscope@v0.37.3-0.20230725203016-5f6947968bd0/pkg/model/role.go (about)

     1  package model
     2  
     3  import (
     4  	"encoding/json"
     5  	"errors"
     6  	"strings"
     7  )
     8  
     9  var (
    10  	ErrRoleUnknown = ValidationError{errors.New("unknown role")}
    11  )
    12  
    13  type Role int
    14  
    15  const (
    16  	InvalidRole Role = iota
    17  	ReadOnlyRole
    18  	AgentRole
    19  	AdminRole
    20  )
    21  
    22  var roles = map[Role]string{
    23  	AdminRole:    "Admin",
    24  	AgentRole:    "Agent",
    25  	ReadOnlyRole: "ReadOnly",
    26  }
    27  
    28  func (r Role) String() string {
    29  	s, _ := roles[r]
    30  	return s
    31  }
    32  
    33  func (r Role) IsValid() bool {
    34  	_, ok := roles[r]
    35  	return ok
    36  }
    37  
    38  func ParseRole(s string) (Role, error) {
    39  	for k, v := range roles {
    40  		if strings.ToLower(s) == strings.ToLower(v) {
    41  			return k, nil
    42  		}
    43  	}
    44  	return InvalidRole, ErrRoleUnknown
    45  }
    46  
    47  func (r *Role) UnmarshalJSON(b []byte) error {
    48  	var s string
    49  	if err := json.Unmarshal(b, &s); err != nil {
    50  		return err
    51  	}
    52  	*r, _ = ParseRole(s)
    53  	return nil
    54  }
    55  
    56  func (r Role) MarshalJSON() ([]byte, error) {
    57  	return json.Marshal(r.String())
    58  }