github.com/aacfactory/fns@v1.2.86-0.20240310083819-80d667fc0a17/services/authorizations/attributes.go (about) 1 /* 2 * Copyright 2023 Wang Min Xiang 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 * 16 */ 17 18 package authorizations 19 20 import ( 21 "bytes" 22 "github.com/aacfactory/errors" 23 "github.com/aacfactory/json" 24 ) 25 26 type Attribute struct { 27 Key []byte `json:"key" avro:"key"` 28 Value json.RawMessage `json:"value" avro:"value"` 29 } 30 31 type Attributes []Attribute 32 33 func (attributes *Attributes) Get(key []byte, value interface{}) (has bool, err error) { 34 attrs := *attributes 35 for _, attribute := range attrs { 36 if bytes.Equal(key, attribute.Key) { 37 decodeErr := json.Unmarshal(attribute.Value, value) 38 if decodeErr != nil { 39 err = errors.Warning("authorizations: attributes get failed").WithCause(decodeErr).WithMeta("key", string(key)) 40 return 41 } 42 has = true 43 return 44 } 45 } 46 return 47 } 48 49 func (attributes *Attributes) Set(key []byte, value interface{}) (err error) { 50 p, encodeErr := json.Marshal(value) 51 if encodeErr != nil { 52 err = errors.Warning("authorizations: attributes set failed").WithCause(encodeErr).WithMeta("key", string(key)) 53 return 54 } 55 attrs := *attributes 56 attrs = append(attrs, Attribute{ 57 Key: key, 58 Value: p, 59 }) 60 *attributes = attrs 61 return 62 } 63 64 func (attributes *Attributes) Remove(key []byte) { 65 attrs := *attributes 66 n := -1 67 for i, attribute := range attrs { 68 if bytes.Equal(key, attribute.Key) { 69 n = i 70 break 71 } 72 } 73 if n == -1 { 74 return 75 } 76 attrs = append(attrs[:n], attrs[n+1:]...) 77 *attributes = attrs 78 return 79 }